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
我的解答:
首先通過中序遍歷將所有節點的值都存放在一個vector<int> a中,然後遍歷樹,對每個節點加上a中比節點要大的值
這樣寫十分臃腫,時間複雜度也高。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
vector<int> a;
toVector(root, a);
addToGreater(root, a);
return root;
}
void addToGreater(TreeNode* root, vector<int>& a){
if(!root){
return;
}
int temp = root->val;
for(int i = 0; i < a.size(); i++){
if(a[i] > temp){
root->val += a[i];
}
}
addToGreater(root->left, a);
addToGreater(root->right, a);
}
void toVector(TreeNode* root, vector<int>& a){
if(!root){
return;
}
toVector(root->left, a);
a.push_back(root->val);
toVector(root->right, a);
}
};
比較好的做法是直接利用中序遍歷,同時,在類中聲明一個全局的sum變量,初始值爲0。
利用迭代的思想
對於一個結點,他本身需要加上右子樹中所有節點的和,以及父節點已經改變了的值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
addSum(root);
return root;
}
void addSum(TreeNode* root){
if(!root){
return;
}
addSum(root->right);
root->val = (sum += root->val);
addSum(root->left);
}
};