插入 C++ 中的二叉搜尋樹


假設我們有一棵二叉搜尋樹。我們只寫一個方法,它將執行以作為引數給定的節點的插入操作。我們必須記住,操作完成後,該樹還將保持為 BST。因此,如果樹如下所示 −

如果我們插入 5,那麼樹將變成 −

為了解決這個問題,我們將遵循以下步驟 −

  • 此方法是遞迴的。這稱為 insert(),它採用一個值 v。
  • 如果根為 null,則使用給定的值 v 建立一個節點,並將其作為根
  • 如果根的值 > v,則
    • 根的左節點 := insert(根的左節點,v)
  • 否則根的右節點 := insert(根的右節點,v)
  • 返回根

示例 (C++)

讓我們檢視以下實現方式,以獲得更好的理解 −

 現場演示

#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
      int val;
      TreeNode *left, *right;
      TreeNode(int data){
         val = data;
         left = 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->val == 0 || curr == NULL){
            cout << "null" << ", ";
         }
         else{
            cout << curr->val << ", ";
         }
      }
   }
   cout << "]"<<endl;
}
class Solution {
public:
   TreeNode* insertIntoBST(TreeNode* root, int val) {
      if(!root)return new TreeNode(val);
      if(root->val > val){
         root->left = insertIntoBST(root->left, val);
      }
      else root->right = insertIntoBST(root->right, val);
         return root;
   }
};
main(){
   Solution ob;
   vector<int> v = {4,2,7,1,3};
   TreeNode *root = make_tree(v);
   tree_level_trav(ob.insertIntoBST(root, 5));
}

輸入

[4,2,7,1,3]
5

輸出

[4,2,7,1,3,5]

更新日期:2020 年 4 月 29 日

超過 8 千次瀏覽

啟動您的職業生涯

完成課程獲得證書

開始學習
廣告