0%

958. Check Completeness of a Binary Tree

O(n) time O(n) space

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
auto n = q.front(); q.pop();
if (!n) { // 完全二叉树必须后边所有的都是nullptr
while (!q.empty()) {
auto x = q.front(); q.pop();
if (x) return false;
}
return true;
}
q.push(n->left);
q.push(n->right);
}
return true;
}
};