题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
样例 1:
输入: tree = {}
输出: 0
样例解释: 空树的深度是0。
样例 2:
输入: tree = {1,2,3,#,#,4,5}
输出: 3
样例解释: 树表示如下,深度是3
1
/ \
2 3
/ \
4 5
算法思路
通过比较根节点的左子树和右子树的深度,哪个深度最深,返回哪个再加上1
代码实现(JAVA)
public int maxDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0;
} else {
int left = maxDepth(root.left);
int right = maxDepth(root.right);
int max = left;
if (max < right) {
max = right;
}
return max + 1;
}
}
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}