题目链接https://leetcode.com/submissions/detail/119156148/
题目大意:返回一个二叉树的高度。
法一:深搜,左右子树直接递归(耗时1ms),代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private static int maxDepth(TreeNode root) { 2 if(root == null) { 3 return 0; 4 } 5 int leftDepth = maxDepth(root.left); 6 int rightDepth = maxDepth(root.right); 7 return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); 8 }
法二:广搜,层序遍历,注意记录每层的结点个数,以记录当前层是否遍历完(耗时3ms),代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private static int maxDepth1(TreeNode root) { 2 if(root == null) { 3 return 0; 4 } 5 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 6 queue.offer(root); 7 int depth = 0; 8 int width = 1; 9 while(!queue.isEmpty()) { 10 TreeNode node = queue.poll(); 11 width--; 12 if(node.left != null) { 13 queue.offer(node.left); 14 } 15 if(node.right != null) { 16 queue.offer(node.right); 17 } 18 if(width == 0) { 19 depth++; 20 width = queue.size(); 21 } 22 } 23 return depth; 24 }