Binary Search Tree
Binary Search Tree
• As we know that binary search in a linked list is not a good choice.
• As we can not directly jump to the middle point of the list as required
in binary search.
• But, now it can be implemented using binary tree and making some
changes in the list.
Binary Search Tree.
Searching
• Lets assume, we are searching for 27.
• The procedure is compare the root of all trees (sub-trees).
Binary Search Tree
• If a tree meets the following two conditions then it will be the BST.
• Nodes in the left sub-tree must be less than root (3 less than 8).
• Nodes in the right sub-tree must be greater than root (17 greater than 8).
• As shown:
BST Operations
• INSERT
• SEARCH
• DELETE
• For all operations, tree must meet the conditions of BST
Recap of Data Structure
• Let's remember that a data structure defines two things; a way of
organizing data and a set of operations to manipulate that data.
• For example: Linked list and BST
INSERT(): Inserting a number in BST
• Following pseudocode is used to insert a number in BST.
• Simulating the code: values are 29 and 15.
INSERT() Operation.
• After inserting the values 35, 20 and 25, the BST looks like this.
Time Complexity
• We will find the time complexity by defining the recurrence equation
that defines its running time.
• Let’s make the T(N) its running time, where N is the number of nodes
in the tree.
• Each instruction takes the constant time except two instructions
Time Complexity.
Time Complexity
• After applying the master theorem, you will find that the complexity
of insert is theta log N.
• However, notice that this expression was obtained assuming that the
tree was completely balanced.
Time Complexity
• If numbers are stored in ascending order and BST looks like this.
• Then what will be the time complexity.
• Hint is shown in the figure.
BST: Search
• Searching in a BST (Simulation)
Pseudocode: BST Search
Cases: BST Search
Time Complexity
• Theta log N