Binary Search Tree
A Binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.
For a binary tree to be a binary search tree, the values of all the nodes in the left sub-tree of the root node should be smaller than the root node's value. Also the values of all the nodes in the right sub-tree of the root node should be larger than the root node's value.
Insertion Algorithm¶
- Compare values of the root node and the element to be inserted.
- If the value of the root node is larger, and if a left child exists, then repeat step 1 with root = current root's left child. Else, insert element as left child of current root.
- If the value of the root node is lesser, and if a right child exists, then repeat step 1 with root = current root's right child. Else, insert element as right child of current root.
Deletion Algorithm¶
- Deleting a node with no children: simply remove the node from the tree.
- Deleting a node with one child: remove the node and replace it with its child.
- Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor.
- Note that: inorder successor can be obtained by finding the minimum value in right child of the node.
Sample Code¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
Time Complexity¶
The worst case time complexity of search, insert, and deletion operations is \(\mathcal{O}(h)\) where h is the height of Binary Search Tree. In the worst case, we may have to travel from root to the deepest leaf node. The height of a skewed tree may become \(N\) and the time complexity of search and insert operation may become \(\mathcal{O}(N)\). So the time complexity of establishing \(N\) node unbalanced tree may become \(\mathcal{O}(N^2)\) (for example the nodes are being inserted in a sorted way). But, with random input the expected time complexity is \(\mathcal{O}(NlogN)\).
However, you can implement other data structures to establish Self-balancing binary search tree (which will be taught later), popular data structures that implementing this type of tree include:
- 2-3 tree
- AA tree
- AVL tree
- B-tree
- Red-black tree
- Scapegoat tree
- Splay tree
- Treap
- Weight-balanced tree