Leetcode: Invert Binary Tree

Leetcode: Invert Binary Tree

Invert a binary tree.

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

to

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

The basic idea is to use LinkedHashMap, as it has property - capacity.

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
/**
* Created by hzhou on 2015/6/13.
* Email: [email protected]
*/
public class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}

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

while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode left = node.left;
TreeNode right = node.right;
// exchange left with right
node.left = right;
node.right = left;
if (left != null) {
queue.add(left);
}
if (right != null) {
queue.add(right);
}
}

return root;
}
}