Leetcode 226 - Invert binary tree

Given the root of a binary tree, invert the tree, and return its root.

Example:
img

1
2
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Recusion:

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
/**
* 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}
*/
var invertTree = function(root) {
let result = [];
invert(root, result);
return root;
}
function invert(root, result) {
if (!root) {
return;
}
let tmp = root.left;
root.left = root.right;
root.right = tmp;
invert(root.right, result);
invert(root.left, result);
}

Iteration:

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
/**
* 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}
*/
var invertTree = function(root) {
if (!root) return root;
let stack = [root];
let cur = null;
while (stack.length) {
cur = stack.pop();
let tmp = cur.left;
cur.left = cur.right;
cur.right = tmp;
cur.right && stack.push(cur.right);
cur.left && stack.push(cur.left);
}
return root;
};