The properties that separates a binary search tree from a regular binary tree is
The binary tree on the right isn't a binary search tree because the right subtree of the node "3" contains a value smaller that it.
Algorithm:
if root is None:
# Python program to demonstrate insert operation in binary search tree class Node: def __init__(self,key): self.left = None self.right = None self.value = key # A function to insert a new node with the given key value def insert(root,node): if root is None: root=node else: if root.value<node.value: if root.right is None: root.right=node else: insert(root.right,node) else: if root.left is None: root.left = node else: insert(root.left,node) # A function for inorder tree traversal def inorder(root): if root: inorder(root.left) print(root.value) inorder(root.right) root=Node(9) insert(root,Node(5)) insert(root,Node(2)) insert(root,Node(4)) insert(root,Node(11)) inorder(root)
root=node
else:
if root.value<node.value:
if root.right is None:
root.right=node
else:
insert(root.right,node)
else:
if root.left is None:
root.left = node
else:
insert(root.left,node)
code:
Output:
2
4
5
9
11
Time Complexity:
In worst case, we may have to travel from root to the deepest leaf node.
The worst case time complexity of insertion operation is O(h)
where h is height of Binary Search Tree.
Comments