Check completeness of a binary tree

LeetCode problem 958. Check Completeness of a Binary Tree.

## Problem description

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

```
       1
     /   \
    2     3
   / \   /
  4   5 6

```

**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

```
       1
     /   \
    2     3
   / \     \
  4   5     7

```

**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`

## Analysis

We can follow the similar procedure in Binary tree level-order traversal. But, instead of putting all nodes into the output array, we just need to use a `prev` pointer to check if we have encountered a `null` node but later a valid node. If this happens then we return false. Otherwise, if we have traversed the entire tree, return true.

### Complexity analysis

#### Time complexity

The time complexity to traverse the entire tree is **O(n)**.

#### Space compelexity

Stack
The space complexity on stack is O(1), as we did not use recursion to go over each level.
Heap
We can use BFS to do this. The worst case is a **perfect binary tree**: layer 1 has 1 node, layer 2 has 2 nodes, layer 3 has 4 nodes, layer 4 has 8 nodes, …, and layer *k* has

2

k
−
1

{\displaystyle 2^{k-1}}

 nodes. In other words, the maximum number of elements in the queue is one half of the total number of nodes in the tree.
So the space complexity on heap is O(n).
So total space complexity is **O(n)**.

## Solution

### C++

```
/\*\*
 \* Definition for a binary tree node.
 \* struct TreeNode {
 \* int val;
 \* TreeNode \*left;
 \* TreeNode \*right;
 \* TreeNode() : val(0), left(nullptr), right(nullptr) {}
 \* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 \* TreeNode(int x, TreeNode \*left, TreeNode \*right) : val(x), left(left), right(right) {}
 \* };
 \*/
class Solution {
private:
 // perform level-order traversal on tree
 // return true if it is complete tree, false otherwise
 static bool levelOrderTraversal(TreeNode\* root) {
 // use a prev to keep track of previous node expanded
 TreeNode \*prev = root;

 std::queue<TreeNode\*> BFSQueue;
 BFSQueue.push(root);
 while (!BFSQueue.empty()) {
 TreeNode \*curr = BFSQueue.front();
 TreeNode \*left = curr->left, \*right = curr->right;
 BFSQueue.pop();

 // check left child
 if ((prev == nullptr) && (left != nullptr)) {
 return false;
 }
 else {
 prev = left;
 if (left != nullptr) {
 BFSQueue.push(left);
 }
 }

 // check right child
 if ((prev == nullptr) && (right != nullptr)) {
 return false;
 }
 else {
 prev = right;
 if (right != nullptr) {
 BFSQueue.push(right);
 }
 }
 }

 return true;
 }

public:
 bool isCompleteTree(TreeNode\* root) {
 if (root == nullptr) {
 return true;
 }
 else {
 return levelOrderTraversal(root);
 }
 }
};

```

### Java

```
/\*\*
 \* Definition for a binary tree node.
 \* public class TreeNode {
 \* int val;
 \* TreeNode left;
 \* TreeNode right;
 \* TreeNode() {}
 \* TreeNode(int val) { this.val = val; }
 \* TreeNode(int val, TreeNode left, TreeNode right) {
 \* this.val = val;
 \* this.left = left;
 \* this.right = right;
 \* }
 \* }
 \*/
class Solution {
 // perform level-order traversal on tree
 // return true if it is complete tree, false otherwise
 private static boolean levelOrderTraversal(TreeNode root) {
 // use a prev to keep track of previous node expanded
 TreeNode prev = root;

 Queue<TreeNode> BFSQueue = new ArrayDeque<>();
 BFSQueue.offer(root);
 while (!BFSQueue.isEmpty()) {
 TreeNode curr = BFSQueue.poll();
 TreeNode left = curr.left, right = curr.right;

 // check left child
 if ((prev == null) && (left != null)) {
 return false;
 }
 else {
 prev = left;
 if (left != null) {
 BFSQueue.offer(left);
 }
 }

 // check right child
 if ((prev == null) && (right != null)) {
 return false;
 }
 else {
 prev = right;
 if (right != null) {
 BFSQueue.offer(right);
 }
 }
 }

 return true;
 }

 public boolean isCompleteTree(TreeNode root) {
 if (root == null) {
 return true;
 }
 else {
 return levelOrderTraversal(root);
 }
 }
}

```