[LeetCode] Convert BST to Greater Tree 將二叉搜尋樹BST轉為較大樹
阿新 • • 發佈:2018-12-27
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; } };
參考資料: