logo

Пошук у бінарному дереві пошуку (BST)

Враховуючи а BST , завдання полягає в пошуку вузла в цьому BST .

Для пошуку значення в BST розглядайте його як відсортований масив. Тепер ми можемо легко виконувати операцію пошуку в BST за допомогою Алгоритм бінарного пошуку .



перетворення int в рядок

Алгоритм пошуку ключа в даному бінарному дереві пошуку:

Скажімо, ми хочемо знайти номер X, Починаємо з кореня. Потім:

  • Ми порівнюємо значення, яке шукаємо, зі значенням кореня.
    • Якщо він дорівнює, ми закінчили пошук, якщо він менший, ми знаємо, що нам потрібно перейти до лівого піддерева, тому що в бінарному дереві пошуку всі елементи в лівому піддереві менші, а всі елементи в правому піддереві більші.
  • Повторюйте вищевказаний крок, доки обхід більше не стане можливим
  • Якщо під час будь-якої ітерації ключ знайдено, поверніть True. Інакше False.

Ілюстрація пошуку в BST:

Для кращого розуміння перегляньте ілюстрацію нижче:

bst1



bst2

bst3

bst4



Рекомендована практика. Пошук вузла в BST Спробуйте це!

Програма для реалізації пошуку в 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->ключ = елемент;> >temp->лівий = temp->right = 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->ліворуч = вставити (вузол->ліворуч, клавіша);> >else> if> (key>вузол->ключ)> >node->праворуч = вставити (вузол->праворуч, ключ);> >// 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;> }>

>

>

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->ключ = елемент;> >temp->лівий = temp->right = 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->ліворуч = вставити (вузол->ліворуч, клавіша);> >else> if> (key>вузол->ключ)> >node->праворуч = вставити (вузол->праворуч, ключ);> >// 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;> }>

>

>

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 = вставити(node.right, ключ); // Повертає (незмінений) покажчик вузла return node; } // Службова функція для пошуку ключа в BST Node search(Node root, int key) // Код драйвера public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); // Вставлення вузлів 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); // Знайти ключ int key = 6; // Пошук у BST if (tree.search(tree.root, key) == null) System.out.println(key + ' not found'); else System.out.println(ключ + ' знайдено '); ключ = 60; // Пошук у BST if (tree.search(tree.root, key) == null) System.out.println(key + ' not found'); else System.out.println(ключ + ' знайдено '); } }>

>

>

Python3




# 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) # Повертає (незмінений) покажчик вузла return node # Допоміжна функція для пошуку ключа в BST def search(root, key): # Базові випадки: root is null або ключ присутній у корені, якщо root має значення None або root.key == ключ: повертає root # Ключ більший за ключ root, якщо root.key повертає search(root.right, key) # Ключ менший за root 's key return search(root.left, key) # Код драйвера if __name__ == '__main__': root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert (root, 40) insert(root, 70) insert(root, 60) insert(root, 80) # Ключ, який потрібно знайти key = 6 # Пошук у BST, якщо search(root, key) None: print(key, 'not found') else: print(key, 'found') key = 60 # Пошук у BST, якщо search(root, key) None: print(key, 'not found') else: print(ключ, 'знайдено')>

>

>

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 = Insert(node.right, key); // Повертає (незмінений) покажчик вузла return node; } // Допоміжна функція для пошуку ключа в BST загальнодоступному Node Search(Node root, int key) // Базові випадки: root є нульовим або ключ присутній у root if (root == null // Код драйвера public static void Main () {BinaryTree bt = new BinaryTree(); bt.Insert(root, 20); bt.Insert(root , 40); bt.Insert (корінь, 80); // Пошук у BST ( bt.Search(root, key) == null) Console.WriteLine(key + ' not found'); else Console.WriteLine(key + ' found'); // Пошук у BST if (bt.Search(root, key) == null) Console.WriteLine(key + ' not found'); else Console.WriteLine(key + ' found'); } }>

>

>

Javascript


Команди sql ddl



// 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 = insert(node.right, key); } // Повертає (незмінений) покажчик вузла return node; } // Допоміжна функція для пошуку ключа у функції BST search(root, key) { // Базові випадки: root має значення null або ключ присутній у root if (root === null || root.key === key ) { повернути корінь; } // Ключ більший за ключ root if (root.key return search(root.right, key); } // Ключ менший за ключ root return search(root.left, key); } // Код драйвера = null; вставити (корінь, 30); вставити (корінь, 70); 60); // Ключ, який потрібно знайти, let key = 6; // Пошук у BST if (search(root, key) === null) { console.log(key + ' not) знайдено'); else { console.log(key + ' found'); // Пошук у BST if (search(root, key) === null) { console.log( ключ + ' не знайдено'); else { console.log(ключ + ' знайдено');

> 

6 not found 60 found>

Часова складність: O(h), де h – висота BST.
Допоміжний простір: O(h), де h – висота BST. Це пов’язано з тим, що максимальний обсяг місця, необхідного для зберігання стека рекурсії, буде ч .

Пов'язані посилання: