题解 | #判断是不是完全二叉树#

判断是不是完全二叉树

https://www.nowcoder.com/practice/8daa4dff9e36409abba2adbe413d6fae

在 BSF 时,我们习惯在将子节点加入队列时,进行非空判断
但是对于 "完全二叉树" 这道题,我们恰恰需要保留这些空节点
从而借此判断二叉树的完整性

import java.util.*;


public class Solution {

    public boolean isCompleteTree (TreeNode root) {
        if (root==null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean hasNull = false;
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if (tmp==null) {
                hasNull=true;
                continue;
            }
            if (hasNull) return false;
            queue.offer(tmp.left);
            queue.offer(tmp.right);
        }
        return true;
    }
}
全部评论

相关推荐

06-26 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
06-04 09:27
门头沟学院 Java
点赞 评论 收藏
分享
_mos_:忍耐王
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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