Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell:
思路很简单,【递归地】交换节点的左右子树。
public TreeNode invertTree(TreeNode root)
{
if(root!=null)
change(root);
return root;
}
public void change(TreeNode t)
{
if(t.left!=null)
change(t.left);
if(t.right!=null)
change(t.right);
TreeNode temp=t.right;
t.right=t.left;
t.left=temp;
}