LeetCode 226. Invert Binary Tree
2020-06-02 23:11:46 # leetcode

Problem

226. Invert Binary Tree

1. 题目简述

翻转一棵二叉树。例如:

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

2. 算法思路

一道被大佬吐槽的easy题目。DFS或者BFS均可。

DFS

递归调用invert,前中后序均可。

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 前序
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}

TreeNode temp = root.left;
root.left = root.right;
root.right = temp;

if (root.left != null) {
root.left = invertTree(root.left);
}
if (root.right != null) {
root.right = invertTree(root.right);
}

return root;
}

// 中序
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}

if (root.left != null) {
root.left = invertTree(root.left);
}

TreeNode temp = root.left;
root.left = root.right;
root.right = temp;

if (root.right != null) {
root.right = invertTree(root.right);
}

return root;
}
//后序
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}

if (root.left != null) {
root.left = invertTree(root.left);
}
if (root.right != null) {
root.right = invertTree(root.right);
}

TreeNode temp = root.left;
root.left = root.right;
root.right = temp;

return root;
}
}

BFS

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
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}

Queue<TreeNode> queue = new LinkedList();
queue.add(root);

while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;

if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}

return root;
}
}