题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
由树的深度定义我们可知,若一棵树根节点没有右子树,则树的深度为左子树深度加1;若一棵树根节点没有左子树,则树的深度为右子树深度加1;若一棵树根节点有左子树和右子树,则树的深度为左右子树深度的较大值加1。
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
return getDepth(root);
}
public int getDepth(TreeNode root) {
if(root == null) {
return 0;
}
int leftDepth = getDepth(root.left) + 1;
int rightDepth = getDepth(root.right) + 1;
return Math.max(leftDepth, rightDepth);
}
}
相关题目:平衡二叉树
网友评论