题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
 
题目链接:

 

 

 

 

 

 

 

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int maxDepth = 0;
    public int TreeDepth(TreeNode root) {
        if(null == root){
            return 0;
        }
        getDepth(root,1);
        return maxDepth;
    }
    
    public void getDepth(TreeNode cur,int depth){
        //叶节点判断深度
        if(cur.left == null && cur.right == null){
            if(depth > maxDepth){
                maxDepth = depth;
            }
            return;
        }
        
        //左子树遍历
        if(cur.left != null){
            getDepth(cur.left,depth+1);
        }
        //右子树遍历
        if(cur.right != null){
            getDepth(cur.right,depth+1);
        }
    }
}

 

posted on 2020-06-09 03:12  MoonBeautiful  阅读(53)  评论(0编辑  收藏  举报