Maximum Depth of Binary Tree
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.
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;
}
}
题意仅仅是需要找到最深的子树。不停的递归调用,一直到不存在叶子为止。
需要注意的是类似的,比如判断是否为balanced,需要加上其他的条件。(所有的结点下的子树深度相差都不超过1.)