"07_226" Invert Binary Tree

Source: Internet
Author: User

Invert Binary TreeTotal accepted:54994 Total submissions:130742 difficulty:easy

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.

Through this problem, a good understanding of recursion.  Recursive return is what to consider clearly, you can carefully grind the problem, very good question. C language
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * struct TreeNode *left;6 * struct TreeNode *right;7  * };8  */9 structtreenode* Inverttree (structtreenode*root) {Ten     if(Root = =NULL) One         returnRoot; A     if(Root->left = = NULL && Root->right = =NULL) -         returnRoot; -     Else{ the         structtreenode* temp = root->Right ; -Root->right = root->Left ; -Root->left =temp; -     } +Root->left = Inverttree (root->Left ); -Root->right = Inverttree (root->Right ); +      A     returnRoot; at}

Here is a solution found on the Internet, written in C + +. Since this is an operation on the structure of the actual tree, it is possible to return a value without special control.

1 treenode* inverttree (treenode* root) {2     if  (root) {3         Inverttree (root-> left); 4         Inverttree (root-> right); 5         Std::swap (Root->left, root-> right); 6     }7     return  root; 8 }

"07_226" 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.