Skip to content

Commit b52d058

Browse files
authored
Create 0958-check-completeness-of-a-binary-tree.js
1 parent 44b0e00 commit b52d058

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* Time O(n) | Space O(n)
11+
* LevelOrder traversal | BFS
12+
* https://leetcode.com/problems/check-completeness-of-a-binary-tree/
13+
* @param {TreeNode} root
14+
* @return {boolean}
15+
*/
16+
var isCompleteTree = function(root) {
17+
18+
// get the depth of the tree
19+
// bfs until n-1 level of depth
20+
21+
const getDepth = (node) => {
22+
if(!node) return 0;
23+
return 1 + Math.max(getDepth(node.left), getDepth(node.right));
24+
}
25+
26+
const depth = getDepth(root) - 1;
27+
28+
const q = new Queue();
29+
q.enqueue(root);
30+
31+
const checkLastLevel = (arr) => {
32+
while(arr[arr.length - 1] === null) arr.pop();
33+
34+
let i = 0;
35+
while(i < arr.length) {
36+
if(arr[i] === null) return false;
37+
i++;
38+
}
39+
40+
return true;
41+
}
42+
43+
let i = 0;
44+
while(i < depth) {
45+
46+
let size = q.size();
47+
48+
if(size !== 2**i) return false;
49+
50+
while(size) {
51+
const node = q.dequeue();
52+
if(!node.left && i !== depth-1) return false;
53+
if(!node.right && i !== depth-1) return false;
54+
55+
if(i !== depth - 1){
56+
q.enqueue(node.left);
57+
q.enqueue(node.right);
58+
} else {
59+
60+
if(!node.left) {
61+
q.enqueue(null);
62+
} else {
63+
q.enqueue(node.left);
64+
}
65+
66+
if(!node.right) {
67+
q.enqueue(null);
68+
} else {
69+
q.enqueue(node.right);
70+
}
71+
72+
}
73+
74+
size--;
75+
}
76+
77+
i++;
78+
}
79+
80+
81+
return checkLastLevel(q.toArray());
82+
};

0 commit comments

Comments
 (0)