在 C++ 中将二叉搜索树转换为二叉树,以便将所有大于键值之和添加到每个键值中。
在该教程中,我们将探讨一个程序,该程序将二叉搜索树转换为二叉树,以便将所有大于键值之和添加到每个键值中。
为此,我们将使用一个二叉搜索树。我们的任务是将该树转换为一个二叉树,并将所有大于键值之和添加到当前键值中。这将通过逆序排列给定的二叉搜索树,并保留所有先前元素之和,最后将其添加到当前元素中来实现。
示例
#include <bits/stdc++.h>
using namespace std;
//node structure of BST
struct node{
int key;
struct node* left;
struct node* right;
};
//creating new node with no child
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);
}
//traversing BST in reverse inorder and adding sum
void reverse_BST(struct node *root, int *sum_ptr){
if (root == NULL)
return;
reverse_BST(root->right, sum_ptr);
//adding elements along the way
*sum_ptr = *sum_ptr + root->key;
root->key = *sum_ptr;
reverse_BST(root->left, sum_ptr);
}
//Using sum and updating the values
void change_greater(struct node *root){
int sum = 0;
reverse_BST(root, &sum);
}
//printing inorder traversal
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 << "Given Tree :" << endl;
printInorder(root);
change_greater(root);
cout << endl;
cout << "Modified Tree :" << endl;
printInorder(root);
return 0;
}输出
Given Tree : 2 5 13 Modified Tree : 20 18 13
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP