📘 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).
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
सारांश
- BST: left < node < right; inorder traversal gives sorted order.
- Search, insert and delete average O(log n).
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.