码迷,mamicode.com
首页 > 其他好文 > 详细

Invert Binary Tree

时间:2016-03-17 09:34:23      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Invert Binary Tree

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5286032.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!