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.
題意:求一個二叉樹的最大深度。
思路:
這道題用分治的思路非常容易解決,在根節(jié)點不是null的情況下,一棵樹的最大高度等于左右子樹的最大高度加1.
用深度搜索的方法,也可以找出一條最長的路徑,即最大高度。
用寬度搜索的方法,也能找出最深一層,得到最大高度。
下面是分治解法的代碼:
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return 1 + Math.max(left, right);
}