[Leetcode] Invert Binary Tree

Source: Internet
Author: User

Invert a binary tree.

     4   /     2     7/\   /1   3 6   9

To

     4   /     7     2/\   /9   6 3   1

What about this problem =. = It's interesting to look at the topic profile. hahaha. ~ To be honest, I really hate whiteboard directly to the code.

Because the BTS to be flipped has been given out, Gray often short of a ah ~ so according to their own preferences whatever exchange is good.

Because the BTS has been given here so can be lazy direct exchange (after all, so short), this comparison trickery. The code is as follows.

public class Solution {public    TreeNode inverttree (TreeNode root) {          //invert directlytreenode left=root.left; TreeNode Right=root.right;root.left=inverttree (right), Root.right=inverttree (left), return root;        Special Case        if (root==null) {          return null;}}    }

And then stick to a conventional mindset, which is on the Program Creek. I probably wrote a little bit, too lazy to run. Just put a definite accepted answer.

This is a solid one to see.

Public TreeNode inverttree (TreeNode root) {    linkedlist<treenode> queue = new linkedlist<treenode> ();     if (root!=null) {        queue.add (root);    }     while (!queue.isempty ()) {        TreeNode p = queue.poll ();        if (p.left!=null)            queue.add (p.left);        if (p.right!=null)            queue.add (p.right);         TreeNode temp = p.left;        P.left = p.right;        P.right = temp;    }     return root;    }

[Leetcode] Invert Binary Tree

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.