[lintcode]Maximum Depth of Binary Tree
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.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The maximum depth is 3.
SOLUTION:
这题就可以用到二叉树万能大法-Divide & Conquer,分治法!
思路就是,从局部去考虑,一棵树的最大高度就是左子树最大高度与右子树最大高度的最大值(Math.max(left, right)) 加上本身root占的一个高度(+1)
也就是,左边递归一次求最大值,右边递归求最大值,这两个中最大的值再加 1 ,递归到底的时候就会返回,每次返回都会+1,保证递归是有意义的。具体看代码:
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
//这一步就告诉我们最后开始返回的时候,每返回一次加一次1
int max = Math.max(left, right) + 1;
return max;
}
}
浙公网安备 33010602011771号