Given a binary tree, invert the binary tree and return it.
Look at the example for more details.
Mirror of a Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
Example 1:
Example 2:
Solution
Do tree traversal through the recursion, and swap the left and right pointers with each other.
Code
0 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 |
public class Solution { public TreeNode invertTree(TreeNode root) { if(root!=null){ TreeNode left=invertTree(root.right); TreeNode right=invertTree(root.left); root.left=left; root.right=right; } return root; } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; left = null; right = null; } } |
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.