1. 程式人生 > >175. Invert Binary Tree【LintCode by java】

175. Invert Binary Tree【LintCode by java】

ttr param nod while return not fin isempty 非遞歸

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 }

175. Invert Binary Tree【LintCode by java】