描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
您在真实的面试中是否遇到过这个题?
样例
样例 1:
输入: tree = {}
输出: 0
样例解释: 空树的深度是0。
样例 2:
输入: tree = {1,2,3,#,#,4,5}
输出: 3
样例解释: 树表示如下,深度是3
1
/ \
2 3
/ \
4 5
它将被序列化为{1,2,3,#,#,4,5}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer
*/
public int maxDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0;
}
int resLeft = maxDepth(root.left) + 1;
int resRight = maxDepth(root.right) + 1;
return Math.max(resLeft, resRight);
}
}