C++ 中将二叉搜索树转为更大的总和树
假设我们有一个具有不同值的二叉搜索树的根,我们必须修改它,以便每个节点的新值等于原始树中大于或等于节点值的值之和。我们必须记住我们在处理二叉搜索树,并且这应保持二叉搜索树的特性。因此,如果输入树如下:

则输出树如下:

为了解决这个问题,我们将遵循以下步骤:
设定全局变量:= 0
定义一个递归函数 solve(),它将以根作为输入。
如果根的右子树不为空,则调用 solve(根的右子树)
全局变量:= 全局变量 + 根的值
如果根的左子树不为空,则调用 solve(根的左子树)
返回根
让我们看看以下实现以便更好地理解:
示例
#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:
int global = 0;
TreeNode* bstToGst(TreeNode* root) {
if(root->right)bstToGst(root->right);
if(root->val != 0)
root->val = global = global + root->val;
if(root->left)bstToGst(root->left);
return root;
}
};
main(){
vector<int> v =
{4,1,6,1,2,5,7,NULL,NULL,NULL,3,NULL,NULL,NULL,8};
TreeNode *root = make_tree(v);
Solution ob;
tree_level_trav(ob.bstToGst(root));
}输入
[4,1,6,1,2,5,7,null,null,null,3,null,null,null,8]
输出
[30, 36, 21, 37, 35, 26, 15, null, null, null, 33, null, null, null, 8, ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP