-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvertBinaryTree.js
More file actions
98 lines (81 loc) · 2.52 KB
/
invertBinaryTree.js
File metadata and controls
98 lines (81 loc) · 2.52 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class TreeNode {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class Tree{
constructor(){
this.root = null;
}
insert(node){
let newNode = new TreeNode(node);
if(!this.root){
this.root = newNode;
return ;
}
else {
let current = this.root;
while(true){
if(node < current.value){
if(current.left === null){
current.left = newNode;
return ;
}
else {
current = current.left
}
}
else if(node > current.value) {
if(current.right === null){
current.right = newNode;
return ;
}
else {
current = current.right
}
}
else if(node === current.value) {
return ;
}
}
}
}
}
let tree = new Tree();
tree.insert(4);tree.insert(2);tree.insert(7);tree.insert(1);tree.insert(3);tree.insert(6);tree.insert(9);
/*
Depth First Search Attempt
Time Complexity = O(N) - Because we need to itrate over each and every node in tree
Space Complexity = O(N) - Space Complexity should be Linear because we are using stack as DFS recursion;
*/
function invertBinaryTreeDFS(treeRoot){
if(treeRoot === null) return treeRoot;
let left = invertBinaryTree(treeRoot.left);
let right = invertBinaryTree(treeRoot.right);
treeRoot.right = left;
treeRoot.left = right;
return treeRoot;
}
/*
Breath First Search Attempt
Time Complexity = O(N) - Because we need to itrate over each and every node in tree
Space Complexity = O(W) - Space Complexity should be Linear because we are using queue as BFS recursion;
*/
function invertBinaryTreeBFS(treeRoot){
let queue = [];
queue.push(treeRoot);
while(queue.length){
let poppedNode = queue.shift();
let left = poppedNode.left;
let right = poppedNode.right;
poppedNode.left = right;
poppedNode.right = left;
if(poppedNode.left) queue.push(left);
if(poppedNode.right ) queue.push(right);
}
return treeRoot;
}
// console.log(invertBinaryTreeDFS(tree.root));
// console.log(invertBinaryTreeBFS(tree.root));