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.
The puzzle: very simple recursion.
/** 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==nullptr| | (root->left==nullptr&&root->right==nullptr)) { returnRoot; } Else if(root->left==nullptr) {Root->left=inverttree (root->Right ); Root->right=nullptr; returnRoot; } Else if(root->right==nullptr) {Root->right=inverttree (root->Left ); Root->left=nullptr; returnRoot; } TreeNode* p=root->Left ; Root->left=inverttree (root->Right ); Root->right=Inverttree (P); returnRoot; }};
Leetcode 226. Invert Binary Tree (Recursive)