📘 Lesson · Lesson 80
Binary Search Tree (BST)
Binary Search Tree (BST)
What is a BST?
💡 Note
A Binary Search Tree keeps smaller values on the left and larger on the right, so searching is fast.
Insert and Inorder
C++
#include <iostream>
using namespace std;
struct Node { int data; Node *left, *right; };
Node* newNode(int d){ Node* n=new Node; n->data=d; n->left=n->right=NULL; return n; }
Node* insert(Node* root, int d){
if(!root) return newNode(d);
if(d < root->data) root->left = insert(root->left, d);
else root->right = insert(root->right, d);
return root;
}
void inorder(Node* root){
if(root){ inorder(root->left); cout<<root->data<<" "; inorder(root->right); }
}
int main(){
Node* root=NULL;
int vals[]={50,30,70,20,40};
for(int v:vals) root=insert(root,v);
inorder(root); // 20 30 40 50 70 (sorted)
return 0;
}Output:
20 30 40 50 70
20 30 40 50 70
Summary
- BST: left < node < right; inorder traversal gives sorted order.
- Search, insert and delete average O(log n).
BST क्या है?
💡 Note
Binary Search Tree छोटी values बाएँ और बड़ी दाएँ रखता है, इसलिए searching तेज़ होती है।
Insert और Inorder
C++
#include <iostream>
using namespace std;
struct Node { int data; Node *left, *right; };
Node* newNode(int d){ Node* n=new Node; n->data=d; n->left=n->right=NULL; return n; }
Node* insert(Node* root, int d){
if(!root) return newNode(d);
if(d < root->data) root->left = insert(root->left, d);
else root->right = insert(root->right, d);
return root;
}
void inorder(Node* root){
if(root){ inorder(root->left); cout<<root->data<<" "; inorder(root->right); }
}
int main(){
Node* root=NULL;
int vals[]={50,30,70,20,40};
for(int v:vals) root=insert(root,v);
inorder(root); // 20 30 40 50 70 (sorted)
return 0;
}Output:
20 30 40 50 70
20 30 40 50 70
सारांश
- BST: left < node < right; inorder traversal sorted order देता है।
- Search, insert और delete average O(log n)।