DS Unit2 BST
DS Unit2 BST
Tree
Learning Objectives
Binary Search Tree is a special kind of binary tree in which nodes are
arranged in a specific order. In a binary search tree (BST), each node
contains-
1. Only smaller values in its left sub tree
2. Only larger values in its right sub tree
We can represent such a tree by a
linked data structure in which each
node is an object.
In addition to a key and satellite
data, each node contains attributes
left, right, and p that point to the
nodes corresponding to its left child,
its right child, and its parent,
respectively. If a child or the parent is
missing, the appropriate attribute
contains the value NIL. The root node
Binary Search Tree
If three distinct keys are A, B and C, then 5 distinct binary search trees are-
Binary Search Tree
Binary Search Tree Construction
Construct a Binary Search Tree (BST) for the following sequence of
numbers-
ow inert 70
70 > 50, so insert 70 to the right of 50.
Binary Search Tree Construction
Preorder Traversal:
Root is 100
In left 20 is again parent(like root)
Then left node is 10 and right node
Is 30.
Similarly in right 200 is parent
Then left node is 150 and then right
Node is 300.
Binary Search Tree Traversal
Inorder Traversal-
10 , 20 , 30 , 100 , 150 , 200 , 300
Postorder Traversal-
Rules-
The insertion of a new key always takes place as the child of some
leaf node.
For finding out the suitable leaf node,
Search the key to be inserted from the root node till some leaf We start
node is reached. searching for
Once a leaf node is reached, insert the key as child of that leafvalue 40 from
node. the root node
Consider the following example where key = 40 is inserted in the 100.
given BST- As 40 < 100,
so we search
in 100’s left
subtree.
As 40 > 20, so
we search in
20’s right
subtree.
Binary Search Tree Operation
When it comes to deleting a node from the binary search tree, following
three cases are possible-
Case-01: Deletion Of A Node Having No Child (Leaf Node)-
Just remove / disconnect the leaf node that is to deleted from the tree.
Consider the following example where node with value = 20 is deleted from
the BST-
Binary Search Tree Operation
Time Complexity:
Time complexity of all BST Operations
= O(h).
Here, h = Height of binary search tree
In worst case:
The binary search tree is a skewed
binary search tree.
Height of the binary search tree
becomes n i.e. number of nodes.
So, Time complexity of BST Operations
= O(n).
In this case, binary search tree is as
good as unordered list with no benefits.
Binary Search Tree Operation
In best case,
a) 7 , 5 , 1 , 0 , 3 , 2 , 4 , 6 , 8 , 9
b) 0 , 2 , 4 , 3 , 1 , 6 , 5 , 9 , 8 , 7
c) 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9
d) 9 , 8 , 6 , 4 , 2 , 3 , 0 , 1 , 5 , 7
Answer: c
MCQ
30 , 20 , 10 , 15 , 25 , 23 , 39 , 35 , 42
a) 10 , 20 , 15 , 23 , 25 , 35 , 42 , 39 , 30
b) 15 , 10 , 25 , 23 , 20 , 42 , 35 , 39 , 30
c) 15 , 20 , 10 , 23 , 25 , 42 , 35 , 39 , 30
d) 15 , 10 , 23 , 25 , 20 , 35 , 42 , 39 , 30
Answer: d