JZ38-二叉树深度

二叉树的深度

https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return helper(root);
    }

    public int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        return Math.max(left, right) + 1;
    }
}

/**
 * 关键点:判别队列中某一层节点出队完成的标准是什么?
 * 在出队之前,此时队列中记录的只有某一层节点,所以队列的大小就是某一层节点的个数。
 * 当此个数减到0的时候,则说明该层节点全部出队完成。
 */
class Solution2 {
    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        int deep = 0;
        int size = 0; //用size控制deep增长的次数和时机(同一层的元素没有完全退出队列的时候deep不可以增加)
        while (queue.size() != 0) {
            size = queue.size();
            while (size != 0) {
                TreeNode temp = queue.poll();

//                if (temp != null) { //这种写***多判断一次
//                    list.add(temp.val);
//                    queue.add(temp.left);  //加入空节点会对深度判断有影响
//                    queue.add(temp.right);
//                }

                if (temp.left != null) {
                    queue.add(temp.left);
                }
                if (temp.right != null) {
                    queue.add(temp.right);
                }
                size--; //当size==0时说明同一层的元素遍历完成
            }
            deep++;
        }
        return deep;
    }
}

全部评论

相关推荐

rbjjj:太杂了吧,同学,项目似乎都没深度,都是api调度耶,分层架构思想没有体现出来了,前端没有前端优化前端工程化体现,后端微服务以及分层架构没体现以及数据安全也没体现,核心再改改,注重于计算机网络,工程化,底层原理吧
点赞 评论 收藏
分享
11-12 14:30
已编辑
广东科技学院 前端工程师
迷茫的小刺猬在迎接o...:前端岗位越来越少了,中小厂也更倾向全栈了,更不需要初级或者实习。可能就大厂才会有一些岗位,但是很看学历。
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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