DSA, Database System & Operating System β Data Structure, Lists, Linked Lists and Trees, NEC licence examination syllabus (Nepal Engineering Council).
Three operations, all following the exact same "compare and go left/right" logic.
SearchCompare target to current node; go left if smaller, right if larger, repeat until found or you hit an empty spot.
InsertionSearch for where the value WOULD be found; insert it there as a new leaf.
DeletionTrickiest case: deleting a node with two children requires replacing it with its in-order successor (the smallest value in its right subtree) or predecessor, to preserve the BST ordering property.
Build a tree by inserting 50, 30, 70, 20, 40, 60, 80 in that order:
Case 1 β delete 20 (a leaf). Nothing depends on it, so simply remove it and set its parent's left pointer to null.
Case 2 β one child. Take the tree that remains after 20 was deleted, in which 30 now has only the child 40. Deleting 30 replaces it by that child, so 50's left pointer goes straight to 40.
Case 3 β two children. Go back to the original tree and delete 50, the root. It cannot simply be removed without orphaning a subtree, so it is replaced by its in-order successor: the smallest key in its right subtree, found by going right once and then left as far as possible β here 70, then 60.
After any insertion or deletion, the in-order traversal of a BST must come out sorted. That is the definition of the ordering property, and it is a complete check.
All three operations cost the height of the tree: search descends one level per comparison, insertion is a search followed by attaching a leaf, and deletion is a search plus at most one more descent to find the successor. So O(log n) on a balanced tree and O(n) on a degenerate one β the same dependence on balance that runs through this whole topic.
Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loadingβ¦