A Binary Search Tree (BST) is a special type of Binary Tree that maintains elements in sorted order. It allows for efficient searching, insertion, and deletion operations.
📌 Properties of a Binary Search Tree (BST)
✔ Left Subtree Rule – The left child contains nodes with values less than the parent node.
✔ Right Subtree Rule – The right child contains nodes with values greater than the parent node.
✔ No Duplicate Values – Each value in the BST is unique.
✔ Inorder Traversal Results in Sorted Order – A BST, when traversed in inorder (LNR), returns elements in ascending order.
📌 Example of a BST
Tree Structure
Array Representation (Level Order)
- Left of 50 → 30 (less than 50)
- Right of 50 → 70 (greater than 50)
- Left of 30 → 20, Right of 30 → 40
- Left of 70 → 60, Right of 70 → 80
📌 Operations on a BST
1️⃣ Searching in BST (O(log n))
- Compare the target value with the root.
- If it’s smaller, search the left subtree; if larger, search the right subtree.
- Repeat until the value is found or the subtree is empty.
🔹 Worst Case (Unbalanced Tree): O(n)
🔹 Best/Average Case (Balanced Tree): O(log n)
2️⃣ Insertion in BST (O(log n))
- Start at the root.
- Compare the new value with the root:
- If smaller, move left.
- If greater, move right.
- Insert it at the appropriate position when an empty spot is found.
🔹 Example: Inserting 25 in the above tree:
3️⃣ Deletion in BST (O(log n))
Three cases for deletion:
- Node with no child → Simply remove it.
- Node with one child → Replace it with its child.
- Node with two children → Replace it with its inorder successor (smallest value in the right subtree).
🔹 Example: Deleting 50
- The inorder successor of 50 is 60
- Replace 50 with 60, then delete the original 60
📌 BST Code Implementation in C
🔹 Output:
💡 This confirms that BST maintains elements in sorted order!
📌 Advantages of BST
✅ Efficient Searching (O(log n))
✅ Sorted Order Retrieval using Inorder Traversal
✅ Dynamic and Easy to Modify (Insert/Delete)
📌 Disadvantages of BST
❌ Unbalanced Trees Can Become Slow (O(n)) – If elements are inserted in sorted order, the tree becomes skewed.
❌ Balancing Needed – AVL and Red-Black Trees improve efficiency.
📌 When to Use a BST?
✔ Efficient Searching & Sorting – Used in databases, maps, and sets.
✔ Hierarchical Data Representation – Used in file systems and routers.
✔ Symbol Tables & Dictionaries – Used in compilers and natural language processing.
🌲 Binary Search Trees are a fundamental data structure for fast searching and efficient data management
No comments:
Post a Comment