Insertion dans l'arbre de recherche binaire (BST)

Insertion dans l'arbre de recherche binaire (BST)

Donné un BST , la tâche consiste à insérer un nouveau nœud dans ce BST .

Exemple:

Insertion dans l

Insertion dans l'arborescence de recherche binaire



Comment insérer une valeur dans un arbre de recherche binaire :

Une nouvelle clé est toujours insérée au niveau de la feuille en conservant la propriété de l'arbre de recherche binaire. Nous commençons à rechercher une clé à partir de la racine jusqu'à atteindre un nœud feuille. Une fois qu'un nœud feuille est trouvé, le nouveau nœud est ajouté en tant qu'enfant du nœud feuille. Les étapes ci-dessous sont suivies pendant que nous essayons d'insérer un nœud dans un arbre de recherche binaire :

  • Vérifiez la valeur à insérer (par exemple X ) avec la valeur du nœud actuel (disons Val ) nous sommes dans:
    • Si X est inférieur à Val passer au sous-arbre de gauche.
    • Sinon, passez au sous-arbre de droite.
  • Une fois le nœud feuille atteint, insérez X à sa droite ou à sa gauche en fonction de la relation entre X et la valeur du nœud feuille.

Suivez l'illustration ci-dessous pour une meilleure compréhension :

Illustration:

bst1

Insertion dans BST

bst2

Insertion dans BST

bst3

Insertion dans BST

bst4

Insertion dans BST

bst5

Insertion dans BST

Insertion dans l'arbre de recherche binaire à l'aide de la récursivité :

Vous trouverez ci-dessous l'implémentation de l'opération d'insertion par récursivité.

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>racine->données) {> > // Insert right node data, if the 'value'> > // to be inserted is greater than 'root' node data.> > // Process right nodes.> > root->right = Insérer (racine->droite, valeur);> > }> > 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 = Insérer (racine->gauche, valeur);> > }> > // 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->à gauche);> > cout ' '; Inorder(root->droite); } // Code du pilote int main() { BST b, *root = NULL ; racine = b.Insérer (racine, 50); b.Insérer (racine, 30); b.Insérer(racine, 20); b.Insérer(racine, 40); b.Insérer(racine, 70); b.Insérer(racine, 60); b.Insérer(racine, 80); b.Inorder(racine); renvoie 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->clé = élément ;> > temp->gauche = temp->droite = NULL;> > return> temp;> }> // A utility function to do inorder traversal of BST> void> inorder(> struct> node* root)> {> > if> (root != NULL) {> > inorder(root->à gauche);> > printf> (> '%d '> , root->clé);> > inorder(root->à droite);> > }> }> // 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->left = insert(node->left, key);> > else> if> (key>nœud->clé)> > node->right = insert(node->right, key);> > // 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, clé); // Renvoie le pointeur de nœud (inchangé) return root; } // Cette méthode appelle principalement InorderRec() void inorder() { inorderRec(root); } // Une fonction utilitaire pour // effectuer un parcours dans l'ordre de BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + ''); inorderRec(root.right); } } // Code du pilote public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Créons les BST suivants 50 / 30 70 / / 20 40 60 80 */ tree.insert(50); arbre.insert(30); arbre.insert(20); arbre.insert(40); arbre.insert(70); arbre.insert(60); arbre.insert(80); // Imprimer le parcours dans l'ordre de l'arbre BST.inorder(); } } // Ce code est contribué par 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, clé); // Renvoie le pointeur de nœud (inchangé) return root; } // Cette méthode appelle principalement InorderRec() void inorder() { inorderRec(root); } // Une fonction utilitaire pour // effectuer un parcours dans l'ordre de BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + ' '); inorderRec(root.right); } } // Code du pilote public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Créons les BST suivants 50 / 30 70 / / 20 40 60 80 */ tree.insert(50); arbre.insert(30); arbre.insert(20); arbre.insert(40); arbre.insert(70); arbre.insert(60); arbre.insert(80); // Imprimer le parcours dans l'ordre de l'arbre BST.inorder(); } } // Ce code est contribué par aashish1995>

Javascript




> // 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, clé); // Renvoie le pointeur de nœud (inchangé) return root; } // Cette méthode appelle principalement la fonction InorderRec() inorder() { inorderRec(root); } // Une fonction utilitaire pour // effectuer un parcours dans l'ordre de la fonction BST inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.key+' '); inorderRec(root.right); } } // Code du pilote /* Créons les suivants BST 50 / 30 70 / / 20 40 60 80 */ insert(50); insérer(30); insérer(20); insérer(40); insérer(70); insérer(60); insérer(80); // Imprimer le parcours dans l'ordre du BST inorder(); // Ce code est contribué par Rajput-Ji>

Sortir

20 30 40 50 60 70 80 

Complexité temporelle :

  • La complexité temporelle dans le pire des cas des opérations d’insertion est Oh) h est la hauteur de l'arbre de recherche binaire.
  • Dans le pire des cas, nous devrons peut-être voyager de la racine au nœud feuille le plus profond. La hauteur d'un arbre incliné peut devenir n et la complexité temporelle de l'opération d'insertion peut devenir Sur).

Espace auxiliaire : L'auxiliaire la complexité spatiale de l'insertion dans un arbre de recherche binaire est O(1)

Insertion dans l'arbre de recherche binaire en utilisant une approche itérative :

Au lieu d'utiliser la récursivité, nous pouvons également implémenter l'opération d'insertion de manière itérative en utilisant un boucle while . Vous trouverez ci-dessous l'implémentation utilisant une boucle 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> clé) {> > prev = temp;> > temp = temp->à gauche ;> > }> > else> if> (temp->val prév = temp; temp = temp->droite ; } } if (prev->val> key) prev->left = nœud ; sinon prev->right = nœud ; } // Fonction utilitaire pour imprimer le parcours dans l'ordre void inorder(Node* root) { Node* temp = root; pile st; while (temp != NULL || !st.empty()) { if (temp != NULL) { st.push(temp); temp = temp->gauche; } autre { temp = st.top(); st.pop(); cout ' '; temp = temp->droite ; } } } // Code du pilote int main() { Node* root = NULL; insert(racine, 30); insert(racine, 50); insert(racine, 15); insert(racine, 20); insert(racine, 10); insert(racine, 40); insert(racine, 60); // Appel de fonction pour imprimer le parcours dans l'ordre inorder(root); renvoie 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>touche) {> > prev = temp;> > temp = temp.left;> > }> > else> if> (temp.val prev = temp; temp = temp.right; } } if (prev.val>clé) prev.left = nœud ; sinon prev.right = nœud ; } // Fonction pour imprimer la valeur inorder public void inorder() { Node temp = root; Pile pile = 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>clé):> > prev> => temp> > temp> => temp.left> > elif> (temp.val prev = temp temp = temp.right if (prev.val>key): prev.left = node else: prev.right = node # Fonction pour imprimer le parcours dans l'ordre de BST def inorder(self): temp = self.root stack = [] while (temp != Aucun ou pas (len( stack) == 0)) : if (temp != None) : stack.append(temp) temp = temp.left else : temp = stack.pop() print(str(temp.val) + ' ', end='') temp = temp.right if __name__ == '__main__' : GFG.main([]) # Ce code est contribué par rastogik346.>

C#




// 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>touche) {> > prev = temp;> > temp = temp.left;> > }> > else> if> (temp.val prev = temp; temp = temp.right; } } if (prev.val>clé) prev.left = nœud ; sinon prev.right = nœud ; } // Fonction pour imprimer le parcours dans l'ordre de BST public void inorder() { Node temp = root; Pile pile = new Stack(); while (temp != null || stack.Count != 0) { if (temp != null) { stack.Push(temp); temp = temp.left; } else { temp = stack.Pop(); Console.Write(temp.val + ' '); temp = temp.right; } } } } // Ce code est fourni par 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>touche) {> > prev = temp;> > temp = temp.left;> > }> else> if> (temp.val prev = temp; temp = temp.right; } } if (prev.val>clé) prev.left = nœud ; sinon prev.right = nœud ; } // Fonction pour imprimer la valeur inorder inorder() { let temp = this.root; laissez stack = []; while (temp != null || stack.length> 0) { if (temp != null) { stack.push(temp); temp = temp.left; } else { temp = stack.pop(); console.log(temp.val + ' '); temp = temp.right; } } } } let tree = new BST(); arbre.insert(30); arbre.insert(50); arbre.insert(15); arbre.insert(20); arbre.insert(10); arbre.insert(40); arbre.insert(60); arbre.inorder(); // ce code est contribué par devendrasolunke>

Sortir

10 15 20 30 40 50 60 

Le complexité temporelle de parcours dans l'ordre est Sur) , car chaque nœud est visité une fois.
Le Espace auxiliaire est Sur) , car nous utilisons une pile pour stocker les nœuds pour la récursivité.

Liens connexes:



Top Articles

Catégorie

Des Articles Intéressants