[LeetCode] Invert Binary Tree 翻轉二叉樹

 

Invert a binary tree.html

     4
   /   \
  2     7
 / \   / \
1   3 6   9

tonode

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:
This problem was inspired by this original tweet by Max Howell:post

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

 

// 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便可。代碼以下:url

 

// 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 題目講解彙總(持續更新中...)spa

相關文章
相關標籤/搜索