958. Check Completeness of a Binary Tree #
Problem #
Given the root of a binary tree, determine if it is a complete binary tree.
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.
Example 1:

Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:

Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
- The number of nodes in the tree is in the range
[1, 100]. 1 <= Node.val <= 1000
Problem Summary #
Given a binary tree, determine whether it is a complete binary tree.
Baidu Baike defines a complete binary tree as follows:
If the depth of a binary tree is h, except for the h-th level, the number of nodes on all other levels (1~h-1) reaches the maximum, and all nodes on the h-th level are continuously concentrated on the far left; this is a complete binary tree. (Note: the h-th level may contain 1~ 2h nodes.)
Solution #
- This problem is a variant of level-order traversal.
- Determine whether each node’s left child is empty.
- Similar problems, Problems 102, 107, and 199, are all level-order traversal.
Code #
package leetcode
import (
"github.com/halfrost/leetcode-go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isCompleteTree(root *TreeNode) bool {
queue, found := []*TreeNode{root}, false
for len(queue) > 0 {
node := queue[0] //Take out the first node of each level
queue = queue[1:]
if node == nil {
found = true
} else {
if found {
return false // A nil appears between two non-empty nodes in level-order traversal
}
//If the left child is nil, then the appended node.Left is nil
queue = append(queue, node.Left, node.Right)
}
}
return true
}