forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComplete Binary Tree Inserter.js
55 lines (51 loc) · 1.26 KB
/
Complete Binary Tree Inserter.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
*/
var CBTInserter = function(root) {
this.root = root;
};
/**
* @param {number} val
* @return {number}
*/
CBTInserter.prototype.insert = function(val) {
let cur = this.root;
let queue = [cur];
while(queue.length){
let updatedQueue = [];
while(queue.length){
let node = queue.shift();
if(!node.left) {
node.left = new TreeNode(val);
return node.val;
}
else updatedQueue.push(node.left);
if(!node.right) {
node.right = new TreeNode(val);
return node.val;
}
else updatedQueue.push(node.right);
}
queue = updatedQueue ;
}
};
/**
* @return {TreeNode}
*/
CBTInserter.prototype.get_root = function() {
return this.root;
};
/**
* Your CBTInserter object will be instantiated and called as such:
* var obj = new CBTInserter(root)
* var param_1 = obj.insert(val)
* var param_2 = obj.get_root()
*/