Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST.
Examples:
Input: Root of following BST
5
/ \
2 13
Output: The given BST is converted to following Binary Tree
18
/ \
20 13
使用递归的方法,递归函数定义为 convert(Node* root, int& sum),root是子树的根节点,sum是该子树所有节点的和。
方法一代码如下:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int value; Node* lchild; Node* rchild;
Node(int val, Node* lch, Node* rch):value(val), lchild(lch), rchild(rch) {}
};
void convert(Node* root, int& sum)
{
if(root==NULL)
return;
convert(root->rchild, sum);
root->value = sum + root->value;
sum = root->value;
convert(root->lchild, sum);
}
void print(Node* root)
{
if(root){
printf("%d|",root->value);
print(root->lchild); print(root->rchild);
}
}
int main()
{
Node* n1 = new Node(1,NULL,NULL);
Node* n3 = new Node(3,NULL,NULL);
Node* n2 = new Node(2,n1,n3);
Node* n5 = new Node(5,NULL,NULL);
Node* n4 = new Node(4,n2,n5);
/* Constructed binary tree is
4
/ \
2 5
/ \
1 3
*/
int sum = 0; convert(n4, sum);
// convert(n4, 15) is wrong, since a temporary object cannot be assigned to a non-const reference
print(n4);
getchar();
return 0;
}
方法二也采用递归:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int value; Node* lchild; Node* rchild;
Node(int val, Node* lch, Node* rch):value(val), lchild(lch), rchild(rch) {}
};
void convert(Node* root, int& sum)
{
if(root==NULL)
return;
if(root->lchild)
convert(root->lchild, sum);
int temp = root->value;
root->value = sum;
sum = sum - temp;
convert(root->rchild, sum);
}
void print(Node* root)
{
if(root){
printf("%d|",root->value);
print(root->lchild); print(root->rchild);
}
}
int main()
{
Node* n1 = new Node(1,NULL,NULL);
Node* n3 = new Node(3,NULL,NULL);
Node* n2 = new Node(2,n1,n3);
Node* n5 = new Node(5,NULL,NULL);
Node* n4 = new Node(4,n2,n5);
/* Constructed binary tree is
4
/ \
2 5
/ \
1 3
*/
int sum = 15; convert(n4, sum);
// convert(n4, 15) is wrong, since a temporary object cannot be assigned to a non-const reference
print(n4);
getchar();
return 0;
}