Code With Python
39K subscribers
841 photos
24 videos
22 files
746 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: Data Structures – Trees – Part 2 of 4: Binary Search Trees (BST)

---

### 1. What is a Binary Search Tree (BST)?

A Binary Search Tree (BST) is a binary tree where all nodes follow the below properties:

• The left child of a node contains only nodes with values less than the node's value.
• The right child of a node contains only nodes with values greater than the node's value.
• Both left and right subtrees must also be BSTs.

This property allows for efficient searching, insertion, and deletion.

---

### 2. Why Use BSTs?

Search operations are faster than in linear structures (like lists).
Ordered traversal becomes very efficient.
• Time complexity (on average):
 • Search: O(log n)
 • Insert: O(log n)
 • Delete: O(log n)
*Worst case is O(n) for skewed trees.*

---

### 3. Implementing a BST in Python

class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None


#### Insert Function:

def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root


#### Example Tree:

root = None
for val in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, val)


This creates:

        50
/ \
30 70
/ \ / \
20 40 60 80


---

### 4. Searching in BST

def search(root, key):
if root is None or root.key == key:
return root
if key < root.key:
return search(root.left, key)
else:
return search(root.right, key)


---

### 5. Finding Minimum and Maximum

def find_min(root):
while root.left:
root = root.left
return root.key

def find_max(root):
while root.right:
root = root.right
return root.key


---

### 6. Deleting a Node in BST

There are 3 cases:

1. Node has no children
2. Node has one child
3. Node has two children

def delete(root, key):
if root is None:
return root

if key < root.key:
root.left = delete(root.left, key)
elif key > root.key:
root.right = delete(root.right, key)
else:
# Node with only one child or no child
if root.left is None:
return root.right
elif root.right is None:
return root.left
# Node with two children
temp = find_min_node(root.right)
root.key = temp.key
root.right = delete(root.right, temp.key)

return root

def find_min_node(node):
while node.left:
node = node.left
return node


---

### 7. Inorder Traversal of BST

Inorder traversal of a BST gives sorted order:

def inorder(root):
if root:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)


---

### 8. Time and Space Complexity Summary

| Operation | Best Case | Average Case | Worst Case |
| --------- | --------- | ------------ | ---------- |
| Search | O(log n) | O(log n) | O(n) |
| Insert | O(log n) | O(log n) | O(n) |
| Delete | O(log n) | O(log n) | O(n) |

*Worst case occurs when tree is skewed (e.g., inserting sorted data)*

---

### 9. Applications of BST

• Search engines
• Sorted maps and sets
• Auto-complete features
• Database indexing
Tree-based dictionaries

---

### 10. Summary

• BST enforces ordering which helps efficient operations
• Insertion, search, and deletion rely on recursive logic
• Traversals help in data processing
• Performance degrades in unbalanced trees — next part will cover balanced trees

---

### Exercise

• Write code to insert, delete, and search in a BST.
• Traverse the BST in inorder, preorder, and postorder.
• Add a function to count number of nodes and leaf nodes.
• Try inserting sorted data and observe tree structure (hint: use print or drawing).

#DSA #DataStructures #Tree #Python

https://t.me/DataScience4
👍32