Invert Binary Tree

Invert a binary tree.

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

将根节点的root.left 与 root.right 交换。
递归调用 左子树与右子树分别进行相同的操作。
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode invertTree(TreeNode root) {
12         if (root == null) {
13             return null;
14         }
15         TreeNode left = invertTree(root.left);
16         TreeNode right = invertTree(root.right);
17         root.left = right;
18         root.right = left;
19         return root;
20         
21     }
22 }

 

posted @ 2016-03-17 09:11  YuriFLAG  阅读(128)  评论(0)    收藏  举报