1. 程式人生 > >104.Maximum Depth of Binary Tree

104.Maximum Depth of Binary Tree

ons lin pan div .com private 分享 nbsp root

題目鏈接https://leetcode.com/submissions/detail/119156148/

題目大意:返回一個二叉樹的高度。

法一:深搜,左右子樹直接遞歸(耗時1ms),代碼如下:

技術分享
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 }
View Code

法二:廣搜,層序遍歷,註意記錄每層的結點個數,以記錄當前層是否遍歷完(耗時3ms),代碼如下:

技術分享
 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 }
View Code

104.Maximum Depth of Binary Tree