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 fuck off.
思路分析:这是最近比较火的一个题目,因为一条推特的转播“Google HR:我们90%的工程师都用你写的软件,但是你竟然不会在白板上面反转一颗二叉树,所以滚吧”,各方看法不一,但看这个题目,的确是一个很简单的题目。考察最基本的递归和树操作。下面给出了递归实现和借助栈的迭代实现(非递归实现)。后一个版本的可扩展性更好,可以处理更大的树。实在是容易题,就是DFS遍历一遍树节点,把每个树节点的左右孩子互换就可以了。或许是那个ios开发牛人不屑于准备就去Google面试,结果被爆,与其说是能力问题,不如说是态度问题。
AC Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode tn){
/*if(tn == null) return null;
TreeNode temp = tn.left;
tn.left = tn.right;
tn.right = temp;
invertTree(tn.left);
invertTree(tn.right);
return tn;*/
//0719
if(tn == null) return null;
Stack<TreeNode> tnStack = new Stack<TreeNode>();
tnStack.push(tn);
while(!tnStack.isEmpty()){
TreeNode cur = tnStack.pop();
TreeNode temp = cur.left;
cur.left = cur.right;
cur.right = temp;
if(cur.left != null) tnStack.push(cur.left);
if(cur.right != null) tnStack.push(cur.right);
}
return tn;
//0726
}
}