Binary Search Tree
Binary Search Tree
A binary tree follows a node based binary tree data structure in order to arrange the elements. A
Binary tree is a binary search tree, when:
• the value of left node must be smaller than the parent node,
• the value of right node must be greater than the parent node.
This rule is applied recursively to the left and right subtrees of the root.
In conclusion the left subtree of a node is smaller than the parent node and right subtree is
greater than the parent node.
In the above figure, we can observe that the root node is 40, and all the nodes of the left
subtree are smaller than the root node, and all the nodes of the right subtree are greater
than the root node.
Similarly, we can see the left child of root node is greater than its left child and smaller
than its right child. So, it also satisfies the property of binary search tree. Therefore, we
can say that the tree in the above image is a binary search tree. Suppose if we change the
value of node 35 to 55 in the above tree, check
whether the tree will be binary search tree or
not.
Advantages of Binary search tree
o Searching an element in the Binary search tree is easy as we always have a hint that
which subtree has the desired element.
o As compared to array and linked lists, insertion and deletion operations are faster
in BST.
Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the root
of the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root of
the right subtree.
Now, let's see the process of inserting a node into BST using an example.