Question
求二叉樹的最大深度
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.
二叉樹的定義
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
Solutions
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
一開始忘記max函數怎么用,就寫成了這樣
if (left > right) {
return left + 1;
} else {
return right + 1;
}
One Line Show
return (root == null) ? 0 : Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);
Points
-
二叉樹的數組表現
[1,null,2,3]這樣的數組,順序為從上往下每行中的從左到右的節點。
null表示空節點。[]表示空樹。
array[i]的左子樹為array[i*2],右子樹為array[i*2+1]。BinaryTree.png 節點為null的處理
if (root == null) {
return 0;
}
-
遞歸的效率
當一個函數用它自己來定義時,就稱為遞歸(recursive)的;紗布如我一開始是這樣寫的
if (maxDepth(root.left) >= maxDepth(root.right)) {
return maxDepth(root.left) + 1;
} else {
return maxDepth(root.right) + 1;
}
多么直觀,然后就感人的Time Limit Exceeded了。
這里大概是因為每次調用一次maxDepth都進行了一次遞歸,所以應該把maxDepth的結果保存成值再進行比較和返回。
這樣寫就沒問題了
int left = maxDepth(root.left);
int right = maxDepth(root.right);
if (left > right) {
return left + 1;
} else {
return right + 1;
}
然后再精簡點
return Math.max(maxDepth(root.right), maxDepth(root.left)) + 1;
TO DO
- 二叉樹相關概念
- Math.max 源碼分析