-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path226. Invert Binary Tree.js
61 lines (52 loc) · 1.24 KB
/
226. 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
/**
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
*/
/**
* Leetcode Fundamenta: 11/5 Update
*
* Failure:
* 1. Fail to think of using BFS
* 2. Fail to think of it will not work passing TreeNode in swap func -> should direct swap
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
// Handle invalid inputs:
if (root === undefined || root === null) return null;
// Level order traversal the tree and swap currNode.left and currNode.right
// Push currNode.left and currNode.right in queue in order
let queue = [root];
while (queue.length !== 0) {
let levelSize = queue.length;
for (let i = 0; i < levelSize; i += 1) {
let currNode = queue.shift();
// Swap currNode.left and currNode.right
[ currNode.left, currNode.right ] = [ currNode.right, currNode.left ];
if (currNode.left !== null) queue.push(currNode.left);
if (currNode.right !== null) queue.push(currNode.right);
}
}
return root;
};