输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
示例1
输入
{1,2,3,4,5,#,6,#,#,7}
输出
4
废话少说直接上代码
节点:
public class TreeNode {
public int val = 0;
public TreeNode left = null;
public TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
处理深度
//定义全局变量记录左子树的深度
int leftDeep = 1;
//定义全局变量记录右子树的深度
int rightDeep = 1;
public int TreeDepth(TreeNode root) {
return TreeDeep(root);
}
private int TreeDeep(TreeNode root) {
if (root==null)//如果是空树直接返回0
return 0;
if (root.left != null) {//递归查询左子树深度
leftDeep++;
TreeDeep(root.left);
}
if (root.right != null) {//递归查询右子树深度
rightDeep++;
TreeDeep(root.right);
}
//返回深度大的数
return leftDeep > rightDeep ? leftDeep : rightDeep;
}