logo

Cercar a l'arbre de cerca binari (BST)

Donat a BST , la tasca és cercar un node en aquest BST .

Per cercar un valor a BST, considereu-lo com una matriu ordenada. Ara podem realitzar fàcilment l'operació de cerca a BST utilitzant Algorisme de cerca binària .

Algorisme per cercar una clau en un arbre de cerca binari determinat:

Suposem que volem cercar el número X, Comencem per l'arrel. Llavors:



  • Comparem el valor a cercar amb el valor de l'arrel.
    • Si és igual acabem amb la cerca si és més petit sabem que hem d'anar al subarbre esquerre perquè en un arbre de cerca binari tots els elements del subarbre esquerre són més petits i tots els elements del subarbre dret són més grans.
  • Repetiu el pas anterior fins que no sigui possible més recorregut
  • Si en qualsevol iteració es troba la clau, retorneu True. Altrament Fals.

Il·lustració de la recerca en un BST:

Vegeu la il·lustració següent per a una millor comprensió:

bst1

bst2

bst3

bst4

Pràctica recomanadaCerqueu un node a BSTTry It!

Programa per implementar la cerca a BST:

C++




// C++ function to search a given key in a given BST> #include> using> namespace> std;> 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> >=>new> struct> node;> >temp->clau = element;> >temp->esquerra = temp->dreta = NULL;> >return> temp;> }> // 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->esquerra = inserir (node->esquerra, clau);> >else> if> (key>node->clau)> >node->dreta = inserir (node->dreta, clau);> >// Return the (unchanged) node pointer> >return> node;> }> // Utility function to search a key in a BST> struct> node* search(>struct> node* root,>int> key)> > >// Base Cases: root is null or key is present at root> >if> (root == NULL> // Driver Code> int> main()> {> >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);> >// Key to be found> >int> key = 6;> >// Searching in a BST> >if> (search(root, key) == NULL)> >cout << key <<>' not found'> << endl;> >else> >cout << key <<>' found'> << endl;> >key = 60;> >// Searching in a BST> >if> (search(root, key) == NULL)> >cout << key <<>' not found'> << endl;> >else> >cout << key <<>' found'> << endl;> >return> 0;> }>

>

transició d'opacitat css

>

C




// C function to search a given key in a given BST> #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->clau = element;> >temp->esquerra = temp->dreta = NULL;> >return> temp;> }> // 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->esquerra = inserir (node->esquerra, clau);> >else> if> (key>node->clau)> >node->dreta = inserir (node->dreta, clau);> >// Return the (unchanged) node pointer> >return> node;> }> // Utility function to search a key in a BST> struct> node* search(>struct> node* root,>int> key)> > // Driver Code> int> main()> {> >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);> >// Key to be found> >int> key = 6;> >// Searching in a BST> >if> (search(root, key) == NULL)> >printf>(>'%d not found '>, key);> >else> >printf>(>'%d found '>, key);> >key = 60;> >// Searching in a BST> >if> (search(root, key) == NULL)> >printf>(>'%d not found '>, key);> >else> >printf>(>'%d found '>, key);> >return> 0;> }>

cadena java adjunta
>

>

Java




// Java program to search a given key in a given BST> class> Node {> >int> key;> >Node left, right;> >public> Node(>int> item) {> >key = item;> >left = right =>null>;> >}> }> class> BinarySearchTree {> >Node root;> >// Constructor> >BinarySearchTree() {> >root =>null>;> >}> >// A utility function to insert> >// a new node with given key in BST> >Node insert(Node node,>int> key) {> >// If the tree is empty, return a new node> >if> (node ==>null>) {> >node =>new> Node(key);> >return> node;> >}> >// Otherwise, recur down the tree> >if> (key node.left = insert(node.left, key); else if (key>node.key) node.right = inserir (node.right, clau); // Retorna el node de retorn del punter del node (no canviat); } // Funció d'utilitat per cercar una clau en una cerca de nodes BST (arrel del node, clau int) // Codi del controlador public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); // Inserint nodes tree.root = tree.insert(tree.root, 50); tree.insert(tree.root, 30); tree.insert(tree.root, 20); tree.insert(tree.root, 40); tree.insert(tree.root, 70); tree.insert(tree.root, 60); tree.insert(tree.root, 80); // Clau per trobar int clau = 6; // Cercant en un BST si (tree.search(tree.root, key) == null) System.out.println(key + 'not found'); else System.out.println(clau + ' trobat'); clau = 60; // Cercant en un BST si (tree.search(tree.root, key) == null) System.out.println(key + 'not found'); else System.out.println(clau + ' trobat'); } }>>>

> 




# Python3 function to search a given key in a given BST> class> Node:> ># Constructor to create a new node> >def> __init__(>self>, key):> >self>.key>=> key> >self>.left>=> None> >self>.right>=> None> # A utility function to insert> # a new node with the given key in BST> def> insert(node, key):> ># If the tree is empty, return a new node> >if> node>is> None>:> >return> Node(key)> ># Otherwise, recur down the tree> >if> key node.left = insert(node.left, key) elif key>node.key: node.right = insert(node.right, key) # Retorna el node de retorn del punter del node (no canviat) # Funció d'utilitat per cercar una clau en una cerca definida BST (arrel, clau): # Casos bàsics: root és null o la clau està present a l'arrel si l'arrel és Cap o root.key == clau: retornar l'arrel # La clau és més gran que la clau de l'arrel si root.key retorna la cerca (arrel.dreta, clau) # La clau és més petita que l'arrel La clau de 's retorna cerca (arrel.esquerra, clau) # Codi del controlador if __name__ == '__main__': arrel = cap arrel = inserir (arrel, 50) inserir (arrel, 30) inserir (arrel, 20) inserir (arrel, 40) inserir (arrel, 70) inserir (arrel, 60) inserir (arrel, 80) # Clau per trobar clau = 6 # Cercar en un BST si cerca (arrel, clau) és Cap: imprimir (clau, 'no trobat') else: print(clau, clau 'trobat') = 60 # Cercar en un BST si cerca (arrel, clau) és Cap: print(clau, 'no trobat') sinó: print(clau, 'trobat')>

>

>

C#




// C# function to search a given key in a given BST> using> System;> public> class> Node {> >public> int> key;> >public> Node left, right;> }> public> class> BinaryTree {> >// A utility function to create a new BST node> >public> Node NewNode(>int> item)> >{> >Node temp =>new> Node();> >temp.key = item;> >temp.left = temp.right =>null>;> >return> temp;> >}> >// A utility function to insert> >// a new node with given key in BST> >public> Node Insert(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 node.left = Insert(node.left, key); else if (key>node.key) node.right = Insereix (node.right, clau); // Retorna el node de retorn del punter del node (no canviat); } // Funció d'utilitat per cercar una clau en una cerca de nodes públics BST (arrel de nodes, clau int) // Cas base: l'arrel és nul·la o la clau està present a l'arrel si (arrel == nul // Codi del controlador public static void Principal () { Node root = null; BinaryTree bt = nou BinaryTree(); , 40); bt.Insert(root, 70); bt.Insert(root, 80); bt.Search(root, key) == null) Console.WriteLine(key + 'not trobat'); else Console.WriteLine(key + ' found'); if (bt.Search(root, key) == null) Console.WriteLine(key + 'not found'); else Console.WriteLine(key + ' found');

> 




// Javascript function to search a given key in a given BST> class Node {> >constructor(key) {> >this>.key = key;> >this>.left =>null>;> >this>.right =>null>;> >}> }> // A utility function to insert> // a new node with given key in BST> function> insert(node, key) {> >// If the tree is empty, return a new node> >if> (node ===>null>) {> >return> new> Node(key);> >}> >// Otherwise, recur down the tree> >if> (key node.left = insert(node.left, key); } else if (key>node.key) { node.right = inserir (node.right, clau); } // Retorna el node de retorn del punter del node (no canviat); } // Funció d'utilitat per cercar una clau en una funció BST cerca (arrel, clau) { // Casos bàsics: l'arrel és nul·la o la clau està present a l'arrel si (arrel === nul || root.key === clau ) { retornar arrel; } // La clau és més gran que la clau de l'arrel si (root.key return search(root.right, key); } // La clau és més petita que la clau de l'arrel retorna la cerca (root.left, key); } // Codi del controlador let root = inserció (arrel, 30) inserció (arrel, 70); 60); insert(root, 80); // Clau per trobar let key = 6 // Cerca en un BST if (search(root, key) === null (key + ' not; trobat'); } else { console.log (clau + ' trobat'); key + ' not found'); else { console.log(key + ' found') }>

>

>

Sortida

hashset java
6 not found 60 found>

Complexitat temporal: O(h), on h és l'alçada del BST.
Espai auxiliar: O(h), on h és l'alçada del BST. Això es deu al fet que la quantitat màxima d'espai necessària per emmagatzemar la pila de recursivitat seria h .

Enllaços relacionats: