Daniel does not have a problem to do, we should do a good job
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.
Recursive solutions:
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: treenode* inverttree (treenode* root) { if (root ==null) return root; treenode* node = inverttree (root->left); Root->left = Inverttree (root->right); root->right = node; return root; }};
Non-recursive solutions:
Treenode* inverttree (treenode* root) { if (root = null) return null; vector<treenode*> Stack; Stack.push_back (root); while (!stack.empty ()) { treenode* node = Stack.back (); Stack.pop_back (); Swap (node->left,node->right); if (node->left) stack.push_back (node->left); if (node->right) stack.push_back (node->right); } return root; }
Python:
def inverttree (self, root): if root: root.left, root.right = Self.inverttree (root.right), Self.inverttree ( Root.left) return rootmaybe make it four lines for better Readability:def inverttree (self, root): if root: in Vert = Self.inverttree root.left, root.right = Invert (root.right), invert (root.left) return Root--------------------------------------------------------------------------------and an iterative version using My own Stack:def inverttree (self, root): stack = [Root] while stack: node = stack.pop () if node: Node.left, node.right = node.right, node.left stack + = Node.left, node.right return root
def inverttree (self, root): If Root is None: return None root.left, root.right = Self.inverttree (root.right ), Self.inverttree (Root.left) return root
Python non-recursive solution:
DFS version:def Inverttree (self, root): if (root): self.inverttree (root.left) Self.inverttree ( Root.right) root.left, root.right = root.right, root.left return root BFS version:def bfs_inverttree (self , root): queue = Collections.deque () if (root): queue.append (Root) while (queue): node = Queue.popleft () if (node.left): queue.append (Node.left) if (node.right): queue.append ( Node.right) node.left, node.right = node.right, node.left return root
Leetcode 226 Invert Binary tree flips two fork trees