-
Notifications
You must be signed in to change notification settings - Fork 6
/
invertTree.js
47 lines (39 loc) · 827 Bytes
/
invertTree.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
// Good morning! Here's your coding interview problem for today.
// This problem was asked by Google.
// Invert a binary tree.
// For example, given the following tree:
// a
// / \
// b c
// / \ /
// d e f
// should become:
// a
// / \
// c b
// \ / \
// f e d
const BST = require("./DataStructures/BST/BinarySearchTree");
let root = new BST();
root.add(10);
root.add(12);
root.add(11);
root.add(13);
root.add(8);
root.add(9);
root.add(7);
function invertTree(root) {
if (root.left || root.right) {
const tempLeft = root.left;
const tempRight = root.right;
[root.left, root.right] = [tempRight, tempLeft];
if (root.left) {
invertTree(root.left);
}
if (root.right) {
invertTree(root.right);
}
}
return root;
}
console.log(invertTree(root).dfsInOrder());