題目描述
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
Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
解析
1.我的方法
先中序遍歷得到遞增序列,求得大於每個結點的結點的val之和,然後再通過DFS算法將其加到每個結點的val上。比較麻煩=.=
class Solution {
private:
vector<int> v;
unordered_map<int,int> mapp;
public:
void inOrder(TreeNode* root){
if(root==NULL) return;
inOrder(root->left);
v.push_back(root->val);
inOrder(root->right);
}
void dfs(TreeNode* root){
if(root==NULL) return;
root->val+=mapp[root->val];
dfs(root->left);
dfs(root->right);
}
TreeNode* convertBST(TreeNode* root) {
inOrder(root);
for(int i=v.size()-1;i>=0;i--){
if(i!=v.size()-1) mapp[v[i]]=v[i+1]+mapp[v[i+1]];
}
dfs(root);
return root;
}
};
2.回溯法
思想:遍歷一個沒有遍歷過的節點之前,先將大於點值的點都遍歷一遍。用到的是反序中序遍歷 。
遞歸算法:首先我們判斷當前訪問的節點是否存在,如果存在就遞歸右子樹,遞歸回來的時候更新總和和當前點的值,然後遞歸左子樹。
class Solution {
private:
int sum=0;
public:
TreeNode* convertBST(TreeNode* root) {
if(root!=NULL){
convertBST(root->right);
sum+=root->val;
root->val=sum;
convertBST(root->left);
}
return root;
}
};