Loading subject…
Inserting the same values in ascending order, 10, 20, 30, 40, 50, gives every node a right child and nothing else.
A BST is worth choosing when data changes often and has to stay in order, and it is the wrong choice when the input arrives already sorted.
| Operation | Balanced BST | Skewed BST | Sorted array | Unsorted array |
|---|---|---|---|---|
| Search | O(log n) | O(n) | O(log n) by binary search | O(n) |
| Insertion | O(log n) | O(n) | O(n), elements shift | O(1) at the end |
| Deletion | O(log n) | O(n) | O(n), elements shift | O(n) |
| Reading values in order | O(n) in-order traversal | O(n) | O(n), already in order | O(n log n), needs a sort first |
The skewed column is why a question that states the data arrives in ascending order is testing whether you spot the degenerate case.
(40) / \ (20) (60) / \ / \ (10) (30) (50) (70)(10) \ (20) \ (30) \ (40) \ (50)Before: (40) After: (40) / \ / \ (20) (60) (30) (60) / \ / \ / / \ (10) (30) (50) (70) (10) (50) (70)Tree: (40) / \ (20) (60) / \ / \ (10) (30) (50) (70)
Pre-order (node, left, right): 40, 20, 10, 30, 60, 50, 70In-order (left, node, right): 10, 20, 30, 40, 50, 60, 70Post-order (left, right, node): 10, 30, 20, 50, 70, 60, 40