-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0226-invert-binary-tree.js
54 lines (43 loc) · 1.09 KB
/
0226-invert-binary-tree.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
/**
* https://leetcode.com/problems/invert-binary-tree/
* TIme O(N) | Space O(N)
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = (root) => {
const isBaseCase = root === null;
if (isBaseCase) return root;
return dfs(root);
}
const dfs = (root) => {
const left = invertTree(root.left);
const right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
/**
* https://leetcode.com/problems/invert-binary-tree/
* TIme O(N) | Space O(W)
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = (root,) => {
const isBaseCase = root === null;
if (isBaseCase) return root;
bfs([ root ]);
return root;
}
const bfs = (queue) => {
while (queue.length) {
for (let i = (queue.length - 1); 0 <= i; i--) {
const node = queue.shift();
const left = node.right;
const right = node.left;
node.left = left;
node.right = right;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
}