1. 程式人生 > >[LeetCode] Binary Tree Upside Down 二叉樹的上下顛倒

[LeetCode] Binary Tree Upside Down 二叉樹的上下顛倒

Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.

For example:

Given a binary tree {1,2,3,4,5},

    1

   / \

  2   3

 / \

4   5

return the root of the binary tree [4,5,2,#,#,3,1].

   4

  / \

 5   2

    / \

   3   1  

這道題讓我們把一棵二叉樹上下顛倒一下,而且限制了右節點要麼為空要麼一定會有對應的左節點。上下顛倒後原來二叉樹的最左子節點變成了根節點,其對應的右節點變成了其左子節點,其父節點變成了其右子節點,相當於順時針旋轉了一下。對於一般樹的題都會有迭代和遞迴兩種解法,這道題也不例外,那麼我們先來看看遞迴的解法。對於一個根節點來說,我們的目標是將其左子節點變為根節點,右子節點變為左子節點,原根節點變為右子節點,那麼我們首先判斷這個根節點是否存在,且其有沒有左子節點,如果不滿足這兩個條件的話,直接返回即可,不需要翻轉操作。那麼我們不停的對左子節點呼叫遞迴函式,直到到達最左子節點開始翻轉,翻轉好最左子節點後,開始回到上一個左子節點繼續翻轉即可,直至翻轉完整棵樹,參見程式碼如下:

解法一:

// Recursion
class Solution {
public:
    TreeNode *upsideDownBinaryTree(TreeNode *root) {
        if (!root || !root->left) return root;
        TreeNode *l = root->left, *r = root->right;
        TreeNode *res = upsideDownBinaryTree(l);
        l->left = r;
        l->right = root;
        root
->left = NULL; root->right = NULL; return res; } };

下面我們來看迭代的方法,和遞迴方法相反的時,這個是從上往下開始翻轉,直至翻轉到最左子節點,參見程式碼如下:

解法二:

// Iterative
class Solution {
public:
    TreeNode *upsideDownBinaryTree(TreeNode *root) {
        TreeNode *cur = root, *pre = NULL, *next = NULL, *tmp = NULL;
        while (cur) {
            next = cur->left;
            cur->left = tmp;
            tmp = cur->right;
            cur->right = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

參考資料: