在 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, ]

更新於: 2020-06-10

109 次瀏覽

開始您的職業生涯

透過完成課程獲得認證

開始
廣告