翻转二叉树(深搜-先序遍历-交换Node)

题目:翻转二叉树,例如

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

to

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

已知二叉树的节点定义如下:

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
}

分析:该题有个小故事:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

该题可以使用深搜中的先序遍历的思路,依次交换左右TreeNode,注意是交换TreeNode,而不是交换TreeNode的值。下面是翻转的过程:

     4                           4                                   4                        4
   /   \                        /  \                                /  \                     / \
  2     7         ->           7    2           ->                 7    2          ->       7   2              
 / \   / \                    / \   / \                           / \  / \                 / \ / \
1  3  6   9                  6   9 1   3                         9  6 1   3               9  6 3  1 

AC代码如下:

    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

 

posted @ 2015-10-27 17:38  lasclocker  阅读(206)  评论(0编辑  收藏  举报