题解 | #二叉树的深度#

二叉树的深度

http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b

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

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

    }

}
*/
import java.util.*;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root==null) return 0;
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return 1+Math.max(left,right);
        //return helper(root);
    }
    /**** 层序遍历 时间O(N)空间O(N) *****/
    public int helper(TreeNode root){
        if(root==null) return 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int high = 0;
        while(!q.isEmpty()){
            int size = q.size();
            for(int i=0;i<size;i++){
                TreeNode cur = q.poll();
                if(cur.left!=null){
                    q.add(cur.left);
                }
                if(cur.right!=null){
                    q.add(cur.right);
                }
            }
            high++;
        }
        return high;
    }
    /**********************************/
}
全部评论

相关推荐

06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
就在我现在公司的隔壁每天经过都唏嘘不已(就是羡慕)什么时候可以到这里上班啊
柯基在debug:从大学毕业投简历到现在了,应届的时候我都面到终面了,现在工作四年了连简历初筛都过不了了
投递莉莉丝游戏等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务