Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ค้นหาโหนดที่มีค่าต่ำสุดใน Binary Search Tree ใน C++


สมมติว่าเรามีต้นไม้การค้นหาแบบไบนารีหนึ่งต้น เราต้องหาองค์ประกอบขั้นต่ำในแผนผังการค้นหาแบบไบนารี ดังนั้นหาก BST อยู่ด้านล่าง −

ค้นหาโหนดที่มีค่าต่ำสุดใน Binary Search Tree ใน C++

องค์ประกอบขั้นต่ำจะเป็น 1

อย่างที่เราทราบกันดีว่าทรีย่อยด้านซ้ายจะมีองค์ประกอบที่เล็กกว่าเสมอ ดังนั้นหากเราสำรวจผ่านทรีย่อยทางซ้ายซ้ำแล้วซ้ำเล่าจนเหลือค่าว่าง เราจะพบองค์ประกอบที่เล็กที่สุด

ตัวอย่าง

#include<iostream>
using namespace std;
class node{
   public:
      node *left;
      int val;
      node *right;
};
node *bst = NULL;
node *getNode(){
   node *newNode;
   newNode = new node;
   return newNode;
}
void insert(node **root, int key){
   node *newNode;
   newNode = getNode();
   newNode->val = key; newNode->left = NULL; newNode->right = NULL;
   if(*root == NULL){
      *root = newNode;
      return;
   } else {
      if(key < (*root)->val)
      insert(&((*root)->left), key);
   else
      insert(&((*root)->right), key);
   }
}
int minElement(){
   node* current = bst;
   while (current->left != NULL) {
      current = current->left;
   }
   return(current->val);
}
main(){
   int item[] = {3, 2, 1, 6, 5, 8};
   int n = sizeof(item)/sizeof(item[0]);
   int i;
   for(i = 0; i<8; i++){
      insert(&bst, item[i]);
   }
   cout << "Minimum element is: " << minElement();
}

ผลลัพธ์

Minimum element is: 1