LeetCode Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
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
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章