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