Check Completeness of a Binary Tree⚓︎
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 2^h
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
Solution⚓︎
BFS⚓︎
- Time complexity: \(O(n)\);
- Space complexity: \(O(n)\).
DFS⚓︎
Starting with the root
node and assigning it an index of 0
, we can use the above property to assign indices to all the other nodes in the tree. Let n
represent the total number of nodes in the tree. As we saw above, the assigned index of every node must be smaller than or equal to n
for the given tree to form a complete binary tree.
If the index
of a node
is greater or equal to n
, it means a node is missing from the first n
indices. In such a case, the tree is not a complete binary tree. The array representation of such a binary tree will have at least one null
node in between non-null nodes.
If index < n
, we proceed to its children. We use index as 2 * index + 1
for the left child node.left and 2 * index + 2
for the right child. Similarly, we determine whether or not the index of the both the children is greater than n
or not.
- Time complexity: \(O(n)\);
- Space complexity: \(O(n)\).