175. Invert Binary Tree【LintCode by java】

Description

Invert a binary tree.

Example

  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

 

 解题:题目要求讲二叉树的左子树和右子树对调一下,用递归来做很简单:
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 public class Solution {
14     /**
15      * @param root: a TreeNode, the root of the binary tree
16      * @return: nothing
17      */
18     public void invertBinaryTree(TreeNode root) {
19         // write your code here
20         if(root == null)
21             return ;
22         TreeNode left = root.left;
23         TreeNode right = root.right;
24         root.left = right;
25         root.right = left;
26         invertBinaryTree(root.left);
27         invertBinaryTree(root.right);
28     }
29 }

非递归法:

 1 public class Solution {
 2     public TreeNode invertTree(TreeNode root) {
 3         Queue<TreeNode> q = new LinkedList<TreeNode>();
 4         if(root!=null) q.offer(root);
 5         while(!q.isEmpty()){
 6             TreeNode curr = q.poll();
 7             TreeNode tmp = curr.right;
 8             curr.right = curr.left;
 9             curr.left = tmp;
10             if(curr.left!=null) q.offer(curr.left);
11             if(curr.right!=null) q.offer(curr.right);
12         }
13         return root;
14     }
15 }

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9192678.html