Tree is a non-linear data structure. It is a hierarchical data structure that has nodes connected through links. The topmost node of the tree which has no parent is known as the root node.
Binary Tree is a form of a tree whose nodes cannot have more than two children. Each node of the binary tree has two pointers associated with it, one points to the left child, and the other points to the right child of the node. It is an unordered tree having no fixed organized structure for the arrangement of nodes.
Note: Binary Tree is slow for the searching, insertion, or deletion of the data because of its unordered structure. The time complexity of these operations is .
Binary Search Tree(BST) is a type of binary tree which is in ordered form. It has a fixed organized structure for the arrangement of nodes. The structure follows the following rules:
Note: BST is faster than a binary tree in the searching, insertion, or deletion of the data because of its ordered structure. The time complexity of these operations is .
We have created a node
class and instantiated the root
node with .
The insert
method compares the value with the value of the root
node and decides whether to insert it on the left or the right side of the BST.
Remember: If the value is lesser than the value of the parent node, it is inserted on the left side; otherwise, it’s inserted on the right side of the BST.
Finally, the PrintTree
method is used to print the BST.
The search
method compares the value with the value of the root
node and if not matched it decides whether to search it on the left or the right side of the BST.
Remember: If the value is lesser than the value of the parent node, it is searched on the left side; otherwise, it’s searched on the right side of the BST.
Free Resources