[Leetcode] Invert binary tree flips two forks

Source: Internet
Author: User

Invert a binary tree.

     4   /     2     7/\   /1   3 6   9

To

     4   /     7     2/\   /9   6 3   1

Trivia:
This problem is inspired by this original tweets by Max Howell:

google:90% of our engineers with the software you wrote (Homebrew), but can ' t invert a binary tree on a Whitebo ard so fuck off.

This problem let us flip two fork tree, is one of the basic operation of the tree, not a problem. The bottom of that sentence is really some wood has moral integrity Ah, do not know is Google said to whom. Anyway, this problem is not very difficult, you can use recursion and non-recursive two methods to solve. First look at the recursive method, the writing is very concise, five lines of code, exchange the current left and right node, and directly call recursion can, code as follows:

// recursion class Solution {public:    TreeNode* Inverttree (treenode* root) {        if return NULL;         *tmp = root-> left;        Root->left = Inverttree (root-> right);        Root->right = inverttree (tmp);         return root;}    };

Non-recursive method is not complex, with the sequence traversal of the binary tree, you need to use queue to assist, first put the root node into the queue, and then take out from the team, exchange its left and right nodes, if there are left to the side of the queue, in order to push until the queue of wood node stop cycle, return to root. The code is as follows:

//non-recursionclassSolution { Public: TreeNode* Inverttree (treenode*root) {        if(!root)returnNULL; Queue<TreeNode*>Q;        Q.push (root);  while(!Q.empty ()) {TreeNode*node =Q.front (); Q.pop (); TreeNode*tmp = node->Left ; Node->left = node->Right ; Node->right =tmp; if(node->left) Q.push (node->Left ); if(node->right) Q.push (node->Right ); }        returnRoot; }};

[Leetcode] Invert binary tree flips two forks

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.