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
一开始的想法,BST树中序遍历是有序的,遍历序列右边都比左边大,所以,先中序遍历得到一数组,然后从后往前做累加,本来想在遍历一遍把树的节点val改掉,但是,还不如第一遍遍历保留了所有的节点指针,然后直接加上去就好。事实证明,方案虽然正确,但是走了好几遍弯路。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
vector<int> helper;
vector<TreeNode*> nodes;
midSearch(root, helper, nodes);
int leftsum = 0;
int nodeAddVal = 0;
for(int i = helper.size() - 1; i >=0; i--)
{
nodeAddVal = helper[i] + leftsum;
leftsum = leftsum + helper[i];
nodes[i]->val = nodeAddVal;
}
return root;
}
void midSearch(TreeNode* root, vector<int>& helper, vector<TreeNode*>& nodes)
{
if(root == nullptr)
return;
midSearch(root->left, helper, nodes);
helper.push_back(root->val);
nodes.push_back(root);
midSearch(root->right, helper, nodes);
}
};
运行结果一般
Runtime: 40 ms, faster than 86.71% of C++ online submissions for Convert BST to Greater Tree.
Memory Usage: 28.7 MB, less than 14.29% of C++ online submissions forConvert BST to Greater Tree.
看了下讨论区,原来可以直接后续遍历不就好了,简单明了直接!
class Solution {
public:
int sum=0;
TreeNode* convertBST(TreeNode* root) {
inorder(root);
return root;
}
void inorder(TreeNode* root)
{
if(root==NULL)
return;
inorder(root->right);
sum+=root->val;
root->val=sum;
inorder(root->left);
}
};