226. Invert Binary Tree

来源:互联网 发布:信捷xc系列编程手册 编辑:程序博客网 时间:2024/06/05 14:58

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   1
Trivia:

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;}


0 0