Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.html
給定一棵兩叉樹,求它的最大深度。node
遞歸求解,遞歸公式
f(n) = 0; n=null,
f(n) = 1+ max(f(n左), f(n右))算法
樹結點類數據結構
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
算法實現類this
public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } else if (root.left == null && root.right == null) { return 1; } else { int left = maxDepth(root.left); int right = maxDepth(root.right); return 1 + (left > right ? left : right); } } }
給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的距離。
樣例:
給出一棵以下的二叉樹:spa
1
/ \
2 3
/ \
4 5
這個二叉樹的最大深度爲3..net
題目來源code
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ static int count = 0; public int maxDepth(TreeNode root) { // write your code here TreeNode last; TreeNode nlast; //定義一個用來存儲結點的隊列 LinkedList<TreeNode> link = new LinkedList<TreeNode>(); last = root; nlast = null; link.add(last); if(root == null) return 0; while(!link.isEmpty()){ TreeNode tn = link.removeFirst();//tn爲根結點 if(tn.left != null ){ link.add(tn.left); nlast = tn.left; } if(tn.right != null ){ link.add(tn.right); nlast = tn.right; } if(tn == last){ last = nlast; count++; } } return count; } }
總結:求二叉樹的最大深度,其實就是求二叉樹的層數(也是按層次打印二叉樹的時候換行的次數),因此這個題咱們只要稍加修改一下按照層次打印二叉樹的代碼就可達到目的。htm
這個是常見的對二叉樹的操做。總結一下:blog
設節點的數據結構,以下:
1 class TreeNode { 2 char val; 3 TreeNode left = null; 4 TreeNode right = null; 5 6 TreeNode(char _val) { 7 this.val = _val; 8 } 9 }
1.二叉樹深度
這個能夠使用遞歸,分別求出左子樹的深度、右子樹的深度,兩個深度的較大值+1便可。
1 // 獲取最大深度 2 public static int getMaxDepth(TreeNode root) { 3 if (root == null) 4 return 0; 5 else { 6 int left = getMaxDepth(root.left); 7 int right = getMaxDepth(root.right); 8 return 1 + Math.max(left, right); 9 } 10 }
2.二叉樹寬度
使用隊列,層次遍歷二叉樹。在上一層遍歷完成後,下一層的全部節點已經放到隊列中,此時隊列中的元素個數就是下一層的寬度。以此類推,依次遍歷下一層便可求出二叉樹的最大寬度。
1 // 獲取最大寬度 2 public static int getMaxWidth(TreeNode root) { 3 if (root == null) 4 return 0; 5 6 Queue<TreeNode> queue = new ArrayDeque<TreeNode>(); 7 int maxWitdth = 1; // 最大寬度 8 queue.add(root); // 入隊 9 10 while (true) { 11 int len = queue.size(); // 當前層的節點個數 12 if (len == 0) 13 break; 14 while (len > 0) {// 若是當前層,還有節點 15 TreeNode t = queue.poll(); 16 len--; 17 if (t.left != null) 18 queue.add(t.left); // 下一層節點入隊 19 if (t.right != null) 20 queue.add(t.right);// 下一層節點入隊 21 } 22 maxWitdth = Math.max(maxWitdth, queue.size()); 23 } 24 return maxWitdth; 25