Skip to content

Commit 0e46136

Browse files
Merge pull request #2785 from Abe0770/main
Create 0958-check-completeness-of-a-binary-tree.cpp
2 parents 1843d43 + 998343b commit 0e46136

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Diff for: cpp/0958-check-completeness-of-a-binary-tree.cpp

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Given the root of a binary tree, determine if it is a complete binary tree.
3+
4+
In a complete binary tree, every level, except possibly the last, is completely filled,
5+
and all nodes in the last level are as far left as possible. It can have between 1 and 2h
6+
nodes inclusive at the last level h.
7+
8+
Ex. Input: root = [1,2,3,4,5,6]
9+
Output: true
10+
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}),
11+
and all nodes in the last level ({4, 5, 6}) are as far left as possible.
12+
13+
Time : O(N);
14+
Space : O(N);
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* struct TreeNode {
20+
* int val;
21+
* TreeNode *left;
22+
* TreeNode *right;
23+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
24+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
25+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
26+
* };
27+
*/
28+
class Solution {
29+
public:
30+
bool isCompleteTree(TreeNode* root) {
31+
queue <TreeNode*> q;
32+
q.push(root);
33+
bool isNull = false;
34+
35+
while(!q.empty()) {
36+
TreeNode * front = q.front();
37+
if(!front)
38+
isNull = true;
39+
else {
40+
if(isNull)
41+
return false;
42+
q.push(front -> left);
43+
q.push(front -> right);
44+
}
45+
q.pop();
46+
}
47+
return true;
48+
}
49+
};

0 commit comments

Comments
 (0)