Invert Binary Tree 解答

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 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4860054.html