958. Check Completeness of a Binary Tree

958. 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:

1
2
3
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
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

Hints/Notes

  • binary tree

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 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 {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
if (root)
q.push(root);
bool end = false;
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
TreeNode* cur = q.front();
q.pop();
if (!cur) {
end = true;
} else {
if (end) {
return false;
}
q.push(cur->left);
q.push(cur->right);
}
}
}
return true;
}
};