Check Completeness of a Binary Tree

Code link: https://leetcode.com/problems/check-completeness-of-a-binary-tree/

Constraint:

  • In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Idea

A full node means a node that contains both left and right child. If we do a level order traversal for a complete binary tree, after we see the first non-full node, all the subsequent nodes must be leaf nodes (no left or right child).

BFS iterative solution:

class Solution {
    public boolean isCompleteTree(TreeNode root) {
        boolean hasNonFullNode = false;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur.left != null) {
                if (hasNonFullNode) {
                    return false;
                }
                
                queue.offer(cur.left);
            } else {
                hasNonFullNode = true;
            }
            
            if (cur.right != null) {
                if (hasNonFullNode) {
                    return false;
                }
                
                queue.offer(cur.right);
            } else {
                hasNonFullNode = true;
            }
        }
        
        return true;
    }
}

Check Completeness of a Binary Tree

上一篇:Pset_ActuatorTypeElectricActuator


下一篇:python学习笔记--Django入门一 网页显示时间