在 C++ 中将 BST 转换为更大的树
假设我们有一个二叉查找树,我们必须将其转换为更大的一棵树,使得原始 BST 的每个键都更改为原始键 + BST 中所有大于原始键的键的总和。
因此,如果输入如下

则输出将是

为此,我们将按照以下步骤进行 −
定义一个函数 revInorder(),它将获取树根 s
如果根为 null,则 −
返回
revInorder(右根,s)
s := s + 根值
根值 := s
revInorder(左根,s)
从主方法中,执行以下操作 −
如果根为 null,则 −
返回 null
sum := 0
revInorder(根,sum)
返回根
示例
让我们看看以下实现以获得更好的理解 −
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}
else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}
else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
}
else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr == NULL || curr->val == 0){
cout << "null" << ", ";
}
else{
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
void revInorder(TreeNode *root,int &s){
if (root == NULL || root->val == 0)
return;
revInorder(root->right, s);
s += root->val;
root->val = s;
revInorder(root->left, s);
}
TreeNode* convertBST(TreeNode* root){
if (root == NULL || root->val == 0)
return NULL;
int sum = 0;
revInorder(root, sum);
return root;
}
};
main(){
Solution ob;
vector<int> v = {5,2,8,NULL,NULL,6,9};
TreeNode *root = make_tree(v);
tree_level_trav(ob.convertBST(root));
}输入
{5,2,8,NULL,NULL,6,9}输出
[28, 30, 17, null, null, 23, 9, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP