Title:
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 whiteboard so Fuck off.
Tips:
This topic investigates the application of function recursion and the swap operation.
Code:
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right ; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: TreeNode* Inverttree (treenode*root) { if(!root)returnNULL; //Save left Nodetreenode* node = root->Left ; //recursively reverse the right node and assign to the left pointerRoot->left = Inverttree (root->Right ); //recursive to the left side of the previously saved node, assigning to the right nodeRoot->right =inverttree (node); returnRoot; }};
"Leetcode" 226. Invert Binary Tree