将BST转换为二叉树,以便将所有更大键的总和添加到C ++中的每个键中
在本教程中,我们将讨论将BST转换为二叉树的程序,以便将所有更大键的总和添加到每个键中。
为此,我们将提供一个二进制搜索树。我们的任务是将该树转换为二进制树,并将所有更大的键的总和添加到当前键中。这将按照给定BST的相反顺序进行,同时具有所有先前元素的总和,最后将其添加到当前元素中。
示例
#include <bits/stdc++.h>
using namespace std;
//BST的节点结构
struct node{
int key;
struct node* left;
struct node* right;
};
//创建没有子节点的新节点
struct node* newNode(int key){
struct node* node = (struct node*)malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
return (node);
}
//以相反的顺序遍历BST并添加总和
void reverse_BST(struct node *root, int *sum_ptr){
if (root == NULL)
return;
reverse_BST(root->right, sum_ptr);
//沿途添加元素
*sum_ptr = *sum_ptr + root->key;
root->key = *sum_ptr;
reverse_BST(root->left, sum_ptr);
}
//使用sum并更新值
void change_greater(struct node *root){
int sum = 0;
reverse_BST(root, &sum);
}
//打印顺序遍历
void printInorder(struct node* node){
if (node == NULL)
return;
printInorder(node->left);
cout << node->key << " " ;
printInorder(node->right);
}
int main(){
node *root = newNode(5);
root->left = newNode(2);
root->right = newNode(13);
cout << "给定树:" << endl;
printInorder(root);
change_greater(root);
cout << endl;
cout << "修改树:" << endl;
printInorder(root);
return 0;
}输出结果
给定树: 2 5 13 修改树: 20 18 13