175. Invert Binary Tree【LintCode by java】

來源:互聯網
上載者:User

標籤:sem   The   int   title   offer   val   nothing   init   node   

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 tree16      * @return: nothing17      */18     public void invertBinaryTree(TreeNode root) {19         // write your code here20         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】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.