[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說給誰的。反正這道題確實難度不大,可以用遞歸和非遞歸兩種方法來解。先來看遞歸的方法,寫法非常簡潔,五行代碼搞定,交換當前左右節點,並直接調用遞歸即可,代碼如下:

 

// Recursion
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return NULL;
        TreeNode *tmp = root->left;
        root->left = invertTree(root->right);
        root->right = invertTree(tmp);
        return root;
    }
};

 

非遞歸的方法也不復雜,跟二叉樹的層序遍歷一樣,需要用queue來輔助,先把根節點排入隊列中,然后從隊中取出來,交換其左右節點,如果存在則分別將左右節點在排入隊列中,以此類推直到隊列中木有節點了停止循環,返回root即可。代碼如下:

 

// Non-Recursion
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return NULL;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode *node = q.front(); q.pop();
            TreeNode *tmp = node->left;
            node->left = node->right;
            node->right = tmp;
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
        return root;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM