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

判断是不是完全二叉树

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;
    }
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务