Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
Solution:
It is a tree problem, so I will give both recursion and iteration solution.
The algorithm is straightforward and I am not going to explain that.
Iteration:
public TreeNode invertTree(TreeNode root) {
if(root==null) return root;
LinkedList<TreeNode> q=new LinkedList<TreeNode>();
q.offer(root);
while(q.size()>0){
TreeNode cur=q.poll();
TreeNode newLeft=cur.right;
TreeNode newRight=cur.left;
cur.right=newRight;
cur.left=newLeft;
if(newLeft!=null) q.offer(newLeft);
if(newRight!=null) q.offer(newRight);
}
return root;
}
Recursion:
public TreeNode invertTree(TreeNode root) {
if(root==null) return root;
TreeNode newLeft=invertTree(root.right);
TreeNode newRight=invertTree(root.left);
root.left=newLeft;
root.right=newRight;
return root;
}
No comments:
Post a Comment