고유한 값을 가진 이진 탐색 트리의 루트가 있다고 가정하고 모든 노드가 노드 값보다 크거나 같은 원래 트리 값의 합과 동일한 새 값을 갖도록 수정해야 합니다. 우리는 이진 탐색 트리를 다루고 있다는 것을 명심해야 하며 이것은 BST의 속성을 유지해야 합니다. 따라서 입력 트리가 다음과 같은 경우 -

그러면 출력 트리는 -
가 됩니다.

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
전역 설정 :=0
-
입력으로 루트를 취하는 재귀 함수 solve()를 정의하십시오.
-
루트의 오른쪽이 null이 아니면 해결(루트의 오른쪽)
-
global :=전역 + 루트 값
-
루트의 왼쪽이 null이 아니면 해결(루트의 왼쪽)
-
루트 반환
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예
#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, ]