-
Notifications
You must be signed in to change notification settings - Fork 0
/
invert-binary-tree.js
50 lines (44 loc) · 1020 Bytes
/
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
/**
* Problem: https://leetcode.com/problems/invert-binary-tree/
/**
* 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
* @return {TreeNode}
*/
// Recursion
function invertTree(root) {
if (root == null) return root;
[root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
return root;
}
// DFS
function invertTree(root) {
const stack = [root];
while (stack.length) {
const n = stack.pop();
if (n != null) {
[n.left, n.right] = [n.right, n.left];
stack.push(n.left, n.right);
}
}
return root;
}
// BFS
function invertTree(root) {
const queue = [root];
while (queue.length) {
const n = queue.shift();
if (n != null) {
[n.left, n.right] = [n.right, n.left];
queue.push(n.left, n.right);
}
}
return root;
}