Topic:
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.
Test instructions: Reverse a binary tree, add a digression, a very simple question, but there is a little story about the problem, click on the link.
Idea 1: Using recursion
Code:
public class solution { TreeNode Inverttree (TreeNode root) { if (root = null | | (Root.left = = null && root.right = null< /span> root; TreeNode temp = Root.right; Root.right = Inverttree (root.left); Root.left = Inverttree (temp); return root; }}
Idea 2: Non-recursive, using stack
Code Listing 2:
Public classSolution { PublicTreeNode inverttree (TreeNode root) {if(Root = =NULL)return NULL; Stack<TreeNode> stack =NewStack<treenode>(); Stack.push (root); while(!Stack.isempty ()) {TreeNode cur=Stack.pop (); TreeNode Temp=Cur.left; Cur.left=Cur.right; Cur.right=temp; if(Cur.left! =NULL) Stack.push (cur.left); if(Cur.right! =NULL) Stack.push (cur.right); } returnRoot; }}
[Leetcode-java] Invert Binary Tree