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]

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

解答

方法一:递归
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
/*
* @Description: 226. Invert Binary Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 递归
* @param {TreeNode} root
* @return {TreeNode}
*/
const invertTree = function (root) {
if (!root) {
return root
}

let temp = root.left
root.left = root.right
root.right = temp

invertTree(root.left)
invertTree(root.right)

return root
}
方法二:层序遍历
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
/*
* @Description: 226. Invert Binary Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 层序遍历
* @param {TreeNode} root
* @return {TreeNode}
*/
const invertTree2 = function (root) {
if (!root) {
return root
}

let queue = [root]

while (queue.length) {
let curNode = queue.shift()
let temp = curNode.left
curNode.left = curNode.right
curNode.right = temp
if (curNode.left) {
queue.push(curNode.left)
}
if (curNode.right) {
queue.push(curNode.right)
}
}

return root
}