[LeetCode] Problem 226 - Invert Binary Tree

Invert a binary tree.

Example

Input:

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

Output:

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

Code

1
2
3
4
5
6
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;

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

return root;
}