二叉搜索树到较大树的转换
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),将其转换为更大的树,使得原始BST的每一个键值更改为原始键值加上比BST中的原始键值大的所有键值的总和。
过程分析
5 5 18 18
/ \ (1) / \ (2)/ \ (3)/ \
2 13 2 13 2 13 20 13
base1::二叉搜索树遍历
void dfs(root) {
if(NULL != root) {
dfs(root->right);
visit(root);
dfs(root->left);
}
}
output:13 5 2
思路:
1. sum初始化为0;
2. 访问右子树,直到右子树为空;
2. 访问根节点,更新节点值,更新sum;
3. 访问左子树,返回到第2步
用下面这个例子,来走一遍。
4
/ \
2 6
/ \ / \
1 3 5 7
官方答案:
void inorder(struct TreeNode* root,int* sum){
if(root!=NULL){
inorder(root->right,sum);
root->val+=*sum;
*sum=root->val;
inorder(root->left,sum);
}
}
struct TreeNode* convertBST(struct TreeNode* root) {
int sum=0;
inorder(root,&sum);
return root;
}