Leetcode 226 Invert Binary Tree 反轉二叉樹

原題地址

https://leetcode.com/problems/invert-binary-tree/

題目描述

Invert a binary tree.
反轉一棵二叉樹。

from

     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:
這個問題的靈感來自Max Howell的原始推文(tweet)

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.
90%的Google員工都在用你寫的軟件(Homebrew),然而你無法在一個白板上寫出反轉二叉樹的算法,所以我們不要你。

關於這個事件,知乎上還有一個討論 如何評價 Homebrew 作者因爲不會在白板上翻轉二叉樹而被谷歌面試拒絕?

此處不作過多討論,看一下這個題就好。

解題思路

直觀上來看,題目要求很清楚,就是左右對調。那麼如何實現呢?可以考慮將每一層的結點從右側開始往左依次添加到一個隊列中,然後把隊列中的結點依次鏈接到上一層的結點上去(假設上一層已經完成了反轉)

要想實現上述思路,我們假設第i-1層已經反轉結束了,正要對第i層執行反轉操作,我們從最右側的結點開始,依次將每個結點node放入隊列queueLast中,並且把每個結點的右孩子和左孩子放入隊列queueCur中(先放右孩子再放左孩子)。這樣處理結束後,queueLast中存儲的就是第i層結點反轉之後的從左至右的順序,然後把queueCur中的結點依次鏈接到queueLast的結點上去即可完成第i層的反轉。

代碼

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return NULL;
        queue<TreeNode*> last, lastTmp, cur, curTmp;
        last.push(root);
        cur.push(root->right);
        cur.push(root->left);

        TreeNode* nodeTop, * nodeBottom;
        while (!last.empty()) {
            while (!last.empty()) { // 把下一層結點鏈接到上一層結點上去
                                    // 並反轉下一層的結點
                nodeTop = last.front();
                last.pop();
                nodeBottom = cur.front();
                cur.pop();
                nodeTop->left = nodeBottom; // 把結點鏈接到上一層結點上去
                if (nodeBottom) {   // 把當前層的結點反轉,放入隊列,以備下層循環使用
                    lastTmp.push(nodeBottom);
                    curTmp.push(nodeBottom->right);
                    curTmp.push(nodeBottom->left);
                }
                nodeBottom = cur.front();
                cur.pop();
                nodeTop->right = nodeBottom; // 把結點鏈接到上一層結點上去
                if (nodeBottom) {   // 把當前層的結點反轉,放入隊列,以備下層循環使用
                    lastTmp.push(nodeBottom);
                    curTmp.push(nodeBottom->right);
                    curTmp.push(nodeBottom->left);
                }
            }
            while (!lastTmp.empty()) {
                last.push(lastTmp.front());
                lastTmp.pop();
            }
            while (!curTmp.empty()) {
                cur.push(curTmp.front());
                curTmp.pop();
            }
        }
        return root;
    }
};

完整代碼 https://github.com/Orange1991/leetcode/blob/master/226/cpp/main.cpp

除此之外,還有用vector實現的一個版本,有興趣可參考https://github.com/Orange1991/leetcode/blob/master/226/cpp/s2.cpp

測試數據

before invert : 4 7 2 1 3 6 9 5 4 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 
after invert : 4 2 7 9 6 3 1 NULL NULL NULL NULL NULL NULL 4 5 NULL NULL NULL NULL 
before invert : 1 2 3 4 NULL NULL 5 NULL NULL NULL NULL 
after invert : 1 3 2 5 NULL NULL 4 NULL NULL NULL NULL 

2015/8/28

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