Poison

226. Invert Binary Tree

Recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}

TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;

invertTree(root.left);
invertTree(root.right);
return root;
}
}
Recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}

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

TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;

return root;
}
}
Recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}

TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);

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

Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}

TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
}

return root;
}
}
Reference

226. Invert Binary Tree
剑指 Offer 27. 二叉树的镜像