[LeetCode] Convert BST to Greater Tree 將二叉搜索樹BST轉為較大樹


 

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13

 

這道題讓我們將二叉搜索樹轉為較大樹,通過題目匯總的例子可以明白,是把每個結點值加上所有比它大的結點值總和當作新的結點值。仔細觀察題目中的例子可以發現,2變成了20,而20是所有結點之和,因為2是最小結點值,要加上其他所有結點值,所以肯定就是所有結點值之和。5變成了18,是通過20減去2得來的,而13還是13,是由20減去7得來的,而7是2和5之和。我開始想的方法是先求出所有結點值之和,然后開始中序遍歷數組,同時用變量sum來記錄累加和,根據上面分析的規律來更新所有的數組。但是通過看論壇,發現還有更巧妙的方法,不用先求出的所有的結點值之和,而是巧妙的將中序遍歷左根右的順序逆過來,變成右根左的順序,這樣就可以反向計算累加和sum,同時更新結點值,叼的不行,參見代碼如下:

 

解法一:

class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        int sum = 0;
        helper(root, sum);
        return root;
    }
    void helper(TreeNode*& node, int& sum) {
        if (!node) return;
        helper(node->right, sum);
        node->val += sum;
        sum = node->val;
        helper(node->left, sum);
    }
};

 

下面這種方法寫的更加簡潔一些,沒有寫其他遞歸函數,而是把自身寫成了可以遞歸調用的函數,參見代碼如下:

 

解法二:

class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        if (!root) return NULL;
        convertBST(root->right);
        root->val += sum;
        sum = root->val;
        convertBST(root->left);
        return root;
    }

private:
    int sum = 0;
};

 

下面這種解法是迭代的寫法,因為中序遍歷有遞歸和迭代兩種寫法,逆中序遍歷同樣也可以寫成迭代的形式,參加代碼如下:

 

解法三:

class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        if (!root) return NULL;
        int sum = 0;
        stack<TreeNode*> st;
        TreeNode *p = root;
        while (p || !st.empty()) {
            while (p) {
                st.push(p);
                p = p->right;
            }
            p = st.top(); st.pop();
            p->val += sum;
            sum = p->val;
            p = p->left;
        }
        return root;
    }
};

 

參考資料:

https://leetcode.com/problems/convert-bst-to-greater-tree/

https://discuss.leetcode.com/topic/83455/java-recursive-o-n-time/2

https://discuss.leetcode.com/topic/83513/one-traverse-java-solution

https://discuss.leetcode.com/topic/83458/java-solution-7-liner-reversed-traversal

 

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


免責聲明!

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



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