이진 검색 트리가 있다고 가정하면 원래 BST의 모든 키가 원래 키 + BST의 원래 키보다 큰 모든 키의 합으로 변경되도록 큰 트리로 변환해야 합니다.
따라서 입력이 다음과 같으면

그러면 출력은

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
revInorder() 함수를 정의하면 트리 루트와 s가 필요합니다.
-
루트가 null이면 -
-
반환
-
-
revInorder(루트의 오른쪽, s)
-
s :=s + 루트의 val
-
루트의 val :=s
-
revInorder(루트 왼쪽, s)
-
기본 방법에서 다음을 수행하십시오 -
-
루트가 null이면 -
-
null 반환
-
-
합계 :=0
-
revInorder(루트, 합계)
-
루트 반환
예시
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#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, ]