Įterpimas į dvejetainį paieškos medį (BST)
Atsižvelgiant į a BST , užduotis yra įterpti naują mazgą BST .
Pavyzdys:
Įterpimas į dvejetainį paieškos medį
Kaip įterpti vertę į dvejetainį paieškos medį:
Naujas raktas visada įterpiamas į lapą išlaikant dvejetainio paieškos medžio savybę. Pradedame ieškoti rakto nuo šaknies, kol nepasiekiame lapo mazgo. Kai randamas lapo mazgas, naujas mazgas pridedamas kaip lapo mazgo antrinis. Bandant įterpti mazgą į dvejetainį paieškos medį, atliekami šie veiksmai:
- Patikrinkite vertę, kurią norite įterpti (tarkim X ) su dabartinio mazgo reikšme (tarkim val ) mes esame:
- Jeigu X mažiau nei val pereiti į kairįjį pomedį.
- Kitu atveju pereikite prie dešiniojo pomedžio.
- Pasiekę lapo mazgą, įdėkite X į dešinę arba į kairę, atsižvelgiant į santykį tarp X ir lapo mazgo vertė.
Norėdami geriau suprasti, vadovaukitės toliau pateikta iliustracija:
Iliustracija:
![]()
Įterpimas į BST
![]()
Įterpimas į BST
![]()
Įterpimas į BST
![]()
Įterpimas į BST
![]()
Įterpimas į BST
Įterpimas į dvejetainį paieškos medį naudojant rekursiją:
Žemiau pateikiamas įterpimo operacijos įgyvendinimas naudojant rekursiją.
C++14
// C++ program to demonstrate insertion> // in a BST recursively> #include> using> namespace> std;> class> BST {> > int> data;> > BST *left, *right;> public> :> > // Default constructor.> > BST();> > // Parameterized constructor.> > BST(> int> );> > // Insert function.> > BST* Insert(BST*,> int> );> > // Inorder traversal.> > void> Inorder(BST*);> };> // Default Constructor definition.> BST::BST()> > : data(0)> > , left(NULL)> > , right(NULL)> {> }> // Parameterized Constructor definition.> BST::BST(> int> value)> {> > data = value;> > left = right = NULL;> }> // Insert function definition.> BST* BST::Insert(BST* root,> int> value)> {> > if> (!root) {> > // Insert the first node, if root is NULL.> > return> new> BST(value);> > }> > // Insert data.> > if> (value>šaknis->duomenys) {> > // Insert right node data, if the 'value'> > // to be inserted is greater than 'root' node data.> > // Process right nodes.> > root->dešinė = Insert(root->right, value);> > }> > else> if> (value data) {> > // Insert left node data, if the 'value'> > // to be inserted is smaller than 'root' node data.> > // Process left nodes.> > root->left = Insert(root->left, value);> > }> > // Return 'root' node, after insertion.> > return> root;> }> // Inorder traversal function.> // This gives data in sorted order.> void> BST::Inorder(BST* root)> {> > if> (!root) {> > return> ;> > }> > Inorder(root->kairėje);> > cout ' '; Inorder(root->teisė); } // Tvarkyklės kodas int main() { BST b, *root = NULL; šaknis = b.Įterpti(šaknis, 50); b.Įterpti(šaknis, 30); b.Įterpti(šaknis, 20); b.Įterpti(šaknis, 40); b.Įterpti(šaknis, 70); b.Įterpti(šaknis, 60); b.Įterpti(šaknis, 80); b.Inorder(šaknis); grąžinti 0; }> |
C
// C program to demonstrate insert> // operation in binary> // search tree.> #include> #include> struct> node {> > int> key;> > struct> node *left, *right;> };> // A utility function to create a new BST node> struct> node* newNode(> int> item)> {> > struct> node* temp> > = (> struct> node*)> malloc> (> sizeof> (> struct> node));> > temp->raktas = prekė;> > temp->kairėje = temp->right = NULL;> > return> temp;> }> // A utility function to do inorder traversal of BST> void> inorder(> struct> node* root)> {> > if> (root != NULL) {> > inorder(root->kairėje);> > printf> (> '%d '> , root->raktas);> > inorder(root->dešinėje);> > }> }> // A utility function to insert> // a new node with given key in BST> struct> node* insert(> struct> node* node,> int> key)> {> > // If the tree is empty, return a new node> > if> (node == NULL)> > return> newNode(key);> > // Otherwise, recur down the tree> > if> (key key)> > node->kairėje = įterpti(mazgas->kairysis, raktas);> > else> if> (key>mazgas->raktas)> > node->dešinė = įterpti(mazgas->dešinėn, raktas);> > // Return the (unchanged) node pointer> > return> node;> }> // Driver Code> int> main()> {> > /* Let us create following BST> > 50> > /> > 30 70> > / /> > 20 40 60 80 */> > struct> node* root = NULL;> > root = insert(root, 50);> > insert(root, 30);> > insert(root, 20);> > insert(root, 40);> > insert(root, 70);> > insert(root, 60);> > insert(root, 80);> > // Print inorder traversal of the BST> > inorder(root);> > return> 0;> }> |
Java
// Java program to demonstrate> // insert operation in binary> // search tree> import> java.io.*;> public> class> BinarySearchTree {> > // Class containing left> > // and right child of current node> > // and key value> > class> Node {> > int> key;> > Node left, right;> > public> Node(> int> item)> > {> > key = item;> > left = right => null> ;> > }> > }> > // Root of BST> > Node root;> > // Constructor> > BinarySearchTree() { root => null> ; }> > BinarySearchTree(> int> value) { root => new> Node(value); }> > // This method mainly calls insertRec()> > void> insert(> int> key) { root = insertRec(root, key); }> > // A recursive function to> > // insert a new key in BST> > Node insertRec(Node root,> int> key)> > {> > // If the tree is empty,> > // return a new node> > if> (root ==> null> ) {> > root => new> Node(key);> > return> root;> > }> > // Otherwise, recur down the tree> > else> if> (key root.left = insertRec(root.left, key); else if (key>root.key) root.right = insertRec(root.right, key); // Grąžina (nepakeista) mazgo rodyklės grąžinimo šaknį; } // Šis metodas daugiausia iškviečia InorderRec() void inorder() { inorderRec(root); } // Naudingumo funkcija, skirta // atlikti BST inorder perėjimą void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + ' '); inorderRec(root.right); } } // Tvarkyklės kodas public static void main(String[] args) { BinarySearchTree medis = new BinarySearchTree(); /* Sukurkime šiuos BST 50 / 30 70 / / 20 40 60 80 */ tree.insert(50); medis.įterpti(30); medis.įterpti(20); medis.įterpti(40); medis.įterpti(70); medis.įterpti(60); medis.įterpti(80); // Spausdinti inorder traversal iš BST medžio.inorder(); } } // Šį kodą sukūrė Ankur Narain Verma> |
Python3
# Python program to demonstrate> # insert operation in binary search tree> # A utility class that represents> # an individual node in a BST> class> Node:> > def> __init__(> self> , key):> > self> .left> => None> > self> .right> => None> > self> .val> => key> # A utility function to insert> # a new node with the given key> def> insert(root, key):> > if> root> is> None> :> > return> Node(key)> > else> :> > if> root.val> => => key:> > return> root> > elif> root.val root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root # A utility function to do inorder tree traversal def inorder(root): if root: inorder(root.left) print(root.val, end=' ') inorder(root.right) # Driver program to test the above functions if __name__ == '__main__': # Let us create the following BST # 50 # / # 30 70 # / / # 20 40 60 80 r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80) # Print inorder traversal of the BST inorder(r)> |
C#
// C# program to demonstrate> // insert operation in binary> // search tree> using> System;> class> BinarySearchTree {> > // Class containing left and> > // right child of current node> > // and key value> > public> class> Node {> > public> int> key;> > public> Node left, right;> > public> Node(> int> item)> > {> > key = item;> > left = right => null> ;> > }> > }> > // Root of BST> > Node root;> > // Constructor> > BinarySearchTree() { root => null> ; }> > BinarySearchTree(> int> value) { root => new> Node(value); }> > // This method mainly calls insertRec()> > void> insert(> int> key) { root = insertRec(root, key); }> > // A recursive function to insert> > // a new key in BST> > Node insertRec(Node root,> int> key)> > {> > // If the tree is empty,> > // return a new node> > if> (root ==> null> ) {> > root => new> Node(key);> > return> root;> > }> > // Otherwise, recur down the tree> > if> (key root.left = insertRec(root.left, key); else if (key>root.key) root.right = insertRec(root.right, key); // Grąžina (nepakeista) mazgo rodyklės grąžinimo šaknį; } // Šis metodas daugiausia iškviečia InorderRec() void inorder() { inorderRec(root); } // Naudingumo funkcija, skirta // atlikti BST inorder perėjimą void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + ' '); inorderRec(root.right); } } // Tvarkyklės kodas public static void Main(String[] args) { BinarySearchTree medis = new BinarySearchTree(); /* Sukurkime šiuos BST 50 / 30 70 / / 20 40 60 80 */ tree.insert(50); medis.įterpti(30); medis.įterpti(20); medis.įterpti(40); medis.įterpti(70); medis.įterpti(60); medis.įterpti(80); // Spausdinti inorder traversal iš BST medžio.inorder(); } } // Šį kodą sukūrė aashish1995>> |
>
>// javascript program to demonstrate>// insert operation in binary>// search tree>>/*>>* Class containing left and right child of current node and key value>>*/>>class Node {>>constructor(item) {>>this>.key = item;>>this>.left =>this>.right =>null>;>>}>>}>>// Root of BST>>var>root =>null>;>>// This method mainly calls insertRec()>>function>insert(key) {>>root = insertRec(root, key);>>}>>// A recursive function to insert a new key in BST>>function>insertRec(root, key) {>>// If the tree is empty, return a new node>>if>(root ==>null>) {>>root =>new>Node(key);>>return>root;>>}>>// Otherwise, recur down the tree>>if>(key root.left = insertRec(root.left, key); else if (key>root.key) root.right = insertRec(root.right, key); // Grąžina (nepakeista) mazgo rodyklės grąžinimo šaknį; } // Šis metodas daugiausia iškviečia InorderRec() funkciją inorder() { inorderRec(root); } // Naudingumo funkcija, skirta // atlikti BST funkcijos inorder perėjimą inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.key+' '); inorderRec(root.right); } } // Tvarkyklės kodas /* Sukurkime taip BST 50 / 30 70 / / 20 40 60 80 */ insert(50); įterpti(30); įterpti(20); įterpti(40); įterpti(70); įterpti(60); įterpti(80); // Spausdinti inorder traversal of BST inorder(); // Šį kodą sukūrė Rajput-Ji>>
>
Laiko sudėtingumas:
- Blogiausiu atveju įterpimo operacijų sudėtingumas yra Oi) kur h yra dvejetainio paieškos medžio aukštis.
- Blogiausiu atveju mums gali tekti keliauti nuo šaknų iki giliausio lapo mazgo. Pasvirusio medžio aukštis gali tapti n ir įterpimo operacijos laiko sudėtingumas gali tapti O(n).
Pagalbinė erdvė: Pagalbinis Įterpimo į dvejetainį paieškos medį erdvės sudėtingumas yra O(1)
Įterpimas į dvejetainį paieškos medį naudojant iteracinį metodą:
Užuot naudoję rekursiją, įterpimo operaciją galime įgyvendinti iteratyviai naudodami a o kilpa . Žemiau pateikiamas įgyvendinimas naudojant ciklą while.
C++
// C++ Code to insert node and to print inorder traversal>// using iteration>#include>using>namespace>std;>// BST Node>class>Node {>public>:>>int>val;>>Node* left;>>Node* right;>>Node(>int>val)>>: val(val)>>, left(NULL)>>, right(NULL)>>{>>}>};>// Utility function to insert node in BST>void>insert(Node*& root,>int>key)>{>>Node* node =>new>Node(key);>>if>(!root) {>>root = node;>>return>;>>}>>Node* prev = NULL;>>Node* temp = root;>>while>(temp) {>>if>(temp->val> raktas) {>>prev = temp;>>temp = temp->paliko;>>}>>else>if>(temp->val prev = temp; temp = temp->dešinė; } } if (prev->val> key) prev->left = mazgas; else prev->right = mazgas; } // Naudingumo funkcija spausdinti inorder traversal void inorder(Node* root) { Node* temp = root; kamino st; while (temp != NULL || !st.empty()) { if (temp != NULL) { st.push(temp); temp = temp->kairė; } else { temp = st.top(); st.pop(); cout ' '; temp = temp->dešinė; } } } // Tvarkyklės kodas int main() { Mazgas* root = NULL; įterpti(šaknis, 30); įterpti(šaknis, 50); įterpti(šaknis, 15); įterpti(šaknis, 20); įterpti(šaknis, 10); įterpti(šaknis, 40); įterpti(šaknis, 60); // Funkcijos iškvietimas spausdinti inorder traversal inorder(root); grąžinti 0; }>
Java
// Java code to implement the insertion>// in binary search tree>import>java.io.*;>import>java.util.*;>class>GFG {>>// Driver code>>public>static>void>main(String[] args)>>{>>BST tree =>new>BST();>>tree.insert(>30>);>>tree.insert(>50>);>>tree.insert(>15>);>>tree.insert(>20>);>>tree.insert(>10>);>>tree.insert(>40>);>>tree.insert(>60>);>>tree.inorder();>>}>}>class>Node {>>Node left;>>int>val;>>Node right;>>Node(>int>val) {>this>.val = val; }>}>class>BST {>>Node root;>>// Function to insert a key>>public>void>insert(>int>key)>>{>>Node node =>new>Node(key);>>if>(root ==>null>) {>>root = node;>>return>;>>}>>Node prev =>null>;>>Node temp = root;>>while>(temp !=>null>) {>>if>(temp.val>raktas) {>>prev = temp;>>temp = temp.left;>>}>>else>if>(temp.val prev = temp; temp = temp.right; } } if (prev.val>raktas) prev.left = mazgas; else prev.right = mazgas; } // Funkcija eilės reikšmės spausdinimui public void inorder() { Node temp = root; Stack stack = new Stack(); while (temp != null || !stack.isEmpty()) { if (temp != null) { stack.add(temp); temp = temp.left; } else { temp = stack.pop(); System.out.print(temp.val + ' '); temp = temp.right; } } } }>
Python3
# Python 3 code to implement the insertion># operation iteratively>class>GFG:>>@staticmethod>>def>main(args):>>tree>=>BST()>>tree.insert(>30>)>>tree.insert(>50>)>>tree.insert(>15>)>>tree.insert(>20>)>>tree.insert(>10>)>>tree.insert(>40>)>>tree.insert(>60>)>>tree.inorder()>class>Node:>>left>=>None>>val>=>0>>right>=>None>>def>__init__(>self>, val):>>self>.val>=>val>class>BST:>>root>=>None>># Function to insert a key in the BST>>def>insert(>self>, key):>>node>=>Node(key)>>if>(>self>.root>=>=>None>):>>self>.root>=>node>>return>>prev>=>None>>temp>=>self>.root>>while>(temp !>=>None>):>>if>(temp.val>raktas):>>prev>=>temp>>temp>=>temp.left>>elif>(temp.val prev = temp temp = temp.right if (prev.val>raktas): prev.left = mazgas else: prev.right = mazgas # Funkcija spausdinti BST def inorder(self) eilės eilutę: temp = self.root stack = [] while (temp != Nėra arba ne (len( stack) == 0)): if (temp != Nėra): stack.append(temp) temp = temp.left else: temp = stack.pop() print(str(temp.val) + ' ', end='') temp = temp.right if __name__ == '__main__': GFG.main([]) # Šį kodą įnešė rastogik346.>>
>
// Function to implement the insertion>// operation iteratively>using>System;>using>System.Collections.Generic;>public>class>GFG {>>// Driver code>>public>static>void>Main(String[] args)>>{>>BST tree =>new>BST();>>tree.insert(30);>>tree.insert(50);>>tree.insert(15);>>tree.insert(20);>>tree.insert(10);>>tree.insert(40);>>tree.insert(60);>>// Function call to print the inorder traversal>>tree.inorder();>>}>}>public>class>Node {>>public>Node left;>>public>int>val;>>public>Node right;>>public>Node(>int>val) {>this>.val = val; }>}>public>class>BST {>>public>Node root;>>// Function to insert a new key in the BST>>public>void>insert(>int>key)>>{>>Node node =>new>Node(key);>>if>(root ==>null>) {>>root = node;>>return>;>>}>>Node prev =>null>;>>Node temp = root;>>while>(temp !=>null>) {>>if>(temp.val>raktas) {>>prev = temp;>>temp = temp.left;>>}>>else>if>(temp.val prev = temp; temp = temp.right; } } if (prev.val>raktas) prev.left = mazgas; else prev.right = mazgas; } // Funkcija spausdinti BST eilės eilės eigą public void inorder() { Mazgo temp = root; Stack stack = new Stack(); while (temp != null || dėklas.Skaičiavimas != 0) { if (temp != null) { kaminas.Push(temp); temp = temp.left; } else { temp = stack.Pop(); Console.Write(temp.val + ' '); temp = temp.right; } } } } // Šį kodą sukūrė Rajput-Ji>
Javascript
// JavaScript code to implement the insertion>// in binary search tree>class Node {>>constructor(val) {>>this>.left =>null>;>>this>.val = val;>>this>.right =>null>;>>}>}>class BST {>>constructor() {>>this>.root =>null>;>>}>>// Function to insert a key>>insert(key) {>>let node =>new>Node(key);>>if>(>this>.root ==>null>) {>>this>.root = node;>>return>;>>}>>let prev =>null>;>>let temp =>this>.root;>>while>(temp !=>null>) {>>if>(temp.val>raktas) {>>prev = temp;>>temp = temp.left;>>}>else>if>(temp.val prev = temp; temp = temp.right; } } if (prev.val>raktas) prev.left = mazgas; else prev.right = mazgas; } // Funkcija spausdinti eilės reikšmę inorder() { let temp = this.root; let stack = []; while (temp != null || kamino.ilgis> 0) { if (temp != null) { stack.push(temp); temp = temp.left; } else { temp = stack.pop(); console.log(temp.val + ' '); temp = temp.right; } } } } tegul medis = new BST(); medis.įterpti(30); medis.įterpti(50); medis.įterpti(15); medis.įterpti(20); medis.įterpti(10); medis.įterpti(40); medis.įterpti(60); medis.inorder(); // šį kodą sukūrė devendrasolunke>>
>
The laiko sudėtingumas apie įsakymo perėjimas yra O(n) , nes kiekvienas mazgas aplankomas vieną kartą.
The Pagalbinė erdvė yra O(n) , nes naudojame krūvą mazgams saugoti rekursijai.Susijusios nuorodos:
- Dvejetainės paieškos medžio paieškos operacija
- Dvejetainės paieškos medžio ištrynimo operacija