Invert a binary tree.
4 / 2 \ 1 3 6 9
To
4 / 7 \ 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.
Recursive method for solving:
/** * Definition forA binary tree node. * struct TreeNode {*intVal * TreeNode * Left; * TreeNode * Right; * TreeNode (intx): Val (x), Left(NULL), Right(NULL) {} * }; */classSolution { Public: treenode* inverttree (treenode* root) {if(!root) returnNULL; Invertnode (root); return root; } void Invertnode (TreeNode *root) {if(Root = =NULL) return;if(!root-> Left&&!root-> Right) return; TreeNode *tempnode=NULL;if(root-> Right) Tempnode = root-> Right;if(root-> Left) {root-> Right= root-> Left; Root-> Left= Tempnode; }Else{root-> Left= Tempnode; Root-> Right=NULL; } invertnode (root-> Left); Invertnode (root-> Right); }};
Leetcode[226]-invert Binary Tree