-
Notifications
You must be signed in to change notification settings - Fork 0
/
invertBinaryTree.js
37 lines (34 loc) · 837 Bytes
/
invertBinaryTree.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
// Invert a binary tree (mirror image)
// https://leetcode.com/problems/invert-binary-tree/description/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// Recursively
var invertTree = function(root) {
if (!root || root.length === 0) return [];
[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);
return root;
};
// Iteratively
var invertTree = function(root) {
if (!root || root.length === 0) return root;
let q = [root];
while (q.length) {
let node = q.shift();
if (node === null) continue;
[node.left, node.right] = [node.right, node.left];
q.push(node.left);
q.push(node.right);
}
return root;
};