175. Invert Binary Tree "Lintcode by Java"

Source: Internet
Author: User
Tags lintcode

Description

Invert a binary tree.

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

 

Problem solving: The topic requires to say two tree Saozi right sub-tree to swap, with the return to do very simple:
1 /**2 * Definition of TreeNode:3 * public class TreeNode {4 * public int val;5 * Public TreeNode left and right;6 * Public TreeNode (int val) {7 * This.val = val;8 * This.left = This.right = null;9  *     }Ten  * } One  */ A  -  Public classSolution { -     /** the      * @paramroot:a TreeNode, the root of the binary tree -      * @return: Nothing -      */ -      Public voidinvertbinarytree (TreeNode root) { +         //Write your code here -         if(Root = =NULL) +             return ; ATreeNode left =Root.left; atTreeNode right =Root.right; -Root.left =Right ; -Root.right =Left ; - Invertbinarytree (root.left); - Invertbinarytree (root.right); -     } in}

Non-recursive method:

1  Public classSolution {2      PublicTreeNode inverttree (TreeNode root) {3queue<treenode> q =NewLinkedlist<treenode>();4         if(root!=NULL) Q.offer (root);5          while(!Q.isempty ()) {6TreeNode Curr =Q.poll ();7TreeNode tmp =Curr.right;8Curr.right =Curr.left;9Curr.left =tmp;Ten             if(curr.left!=NULL) Q.offer (curr.left); One             if(curr.right!=NULL) Q.offer (curr.right); A         } -         returnRoot; -     } the}

175. Invert Binary Tree "Lintcode by Java"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.