牛客地址:二叉树的深度_牛客题霸_牛客网
描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
示例1
输入:
{1,2,3,4,5,#,6,#,#,7} 返回值:
4
代码过于简单,没什么好说的。
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = TreeDepth(root.left) + 1;
int rightDepth = TreeDepth(root.right) + 1;
return leftDepth > rightDepth ? leftDepth : rightDepth;
}