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

Invert Binary Tree 解答

时间:2015-10-08 10:16:31      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

Quetion

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9

to

     4
   /     7     2
 / \   / 9   6 3   1

Solution 1 -- Recursion

Easy to think.

 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 root;
14         TreeNode leftNode = null, rightNode = null;
15         if (root.left != null)
16             leftNode = invertTree(root.left);
17         if (root.right != null)
18             rightNode = invertTree(root.right);
19         root.left = rightNode;
20         root.right = leftNode;
21         return root;
22     }
23 }

 

Solution 2 -- Iteration

BFS

 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 root;
14         List<TreeNode> current = new ArrayList<TreeNode>();
15         List<TreeNode> next;
16         current.add(root);
17         while (current.size() > 0) {
18             next = new ArrayList<TreeNode>();
19             for (TreeNode tmpNode : current) {
20                 // inverse tmpNode
21                 TreeNode left = tmpNode.left;
22                 TreeNode right = tmpNode.right;
23                 tmpNode.right = left;
24                 tmpNode.left = right;
25                 if (right != null)
26                     next.add(right);
27                 if (left != null)
28                     next.add(left);
29             }
30             current = next;
31         }
32         return root;
33     }
34 }

 

Invert Binary Tree 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4860054.html

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