Binary Search Tree¶
A binary search tree (BST) is a specialized type of binary tree that maintains a specific order among its elements. In a BST, each node has at most two children, and the value of the left child is less than the value of the parent node, while the value of the right child is greater than the value of the parent node. This property allows for efficient searching, insertion, and deletion operations.
Defining a tree
graph TD
A[5]
B[1]
C[8]
D[-1]
E[3]
F[7]
G[9]
A --> B
A --> C
B --> D
B --> E
C --> F
C --> G
Recursive in order traversal DFS (Depth First Search)
- Time complexity: O(n) - Each node is visited once.
- Space complexity: O(n) - In the worst case (a completely unbalanced tree).
Search for a value in a binary search tree
- Time complexity: O(log n) - In a balanced BST, the height of the tree is log(n), so the search operation takes logarithmic time.
- Space complexity: O(log n) - In a balanced BST, the height of the tree is log(n), so the space complexity is logarithmic due to the recursive call stack.