二叉树的最大深度
描述
- 给定一个二叉树,找出其最大深度。
- 二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最大深度为3.
考察点
- 递归
答案
private int max;
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int maxDepth(TreeNode root) {
// write your code here
getDepth(root, 1);
return max;
}
public void getDepth(TreeNode root, int num) {
if (root == null) {
max = Math.max(max, num - 1);
return;
}
getDepth(root.left, num + 1);
getDepth(root.right, num + 1);
}