這個是常見的對二叉樹的操做。總結一下:數據結構
設節點的數據結構,以下:this
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.二叉樹深度spa
這個可使用遞歸,分別求出左子樹的深度、右子樹的深度,兩個深度的較大值+1便可。.net
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.二叉樹寬度code
使用隊列,層次遍歷二叉樹。在上一層遍歷完成後,下一層的全部節點已經放到隊列中,此時隊列中的元素個數就是下一層的寬度。以此類推,依次遍歷下一層便可求出二叉樹的最大寬度。blog
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 }
參考:http://blog.csdn.net/htyurencaotang/article/details/12406223遞歸