-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy path0226. Invert Binary Tree.js
83 lines (72 loc) · 1.31 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
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
// Invert a binary tree.
//
// Example:
//
// Input:
//
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
// Output:
//
// 4
// / \
// 7 2
// / \ / \
// 9 6 3 1
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// 1) Recursion
const invertTree1 = (root) => {
const go = (node) => {
if (node == null) return;
const n = node.left;
node.left = node.right;
node.right = n;
go(node.left);
go(node.right);
};
go(root);
return root;
};
// 2) Recursion
const invertTree2 = (root) => {
if (root == null) return root;
[root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
return root;
};
// 3) DFS
const invertTree3 = (root) => {
const st = [root];
while (st.length) {
const n = st.pop();
if (n != null) {
[n.left, n.right] = [n.right, n.left];
st.push(n.left, n.right);
}
}
return root;
};
// 4) BFS
const invertTree = (root) => {
const q = [root];
while (q.length) {
const n = q.shift(); // the only difference with DFS is here
if (n != null) {
[n.left, n.right] = [n.right, n.left];
q.push(n.left, n.right);
}
}
return root;
};