ds31
ds31
The above example of the binary tree represented using Linked list representation is shown as follows,
class BST:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
root=BST(10)
print(root.value)
print(root.left)
print(root.right)
Output:
10
None
None
Time and Space Complexity
The time complexity for the creation of a binary search tree is O(1) because it takes constant time for the
initialization of data variables. The space complexity is O(1) as well since no additional memory is
required.
Search Operation
If we want to know whether a given node is there or not, we will compare the data of the given node with
that in the root node.
First, we need to search whether the root key is equal to the given data. If the given node is present in the
tree, we can print a message.
If the data is less than the root key, we will search on the left subtree, else, we look at the right subtree.
Algorithm
1. Traverse binary search tree
2. Compare input value with every node of BST.
3. At every node, we will make decision about the traversal of BST
Input number is equal node data (We found the element).
Input number is less than node data
Find the element in left subtree.
Input number is greater than node data.
Find the element in right subtree.
Code
class BST:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def insert(self, data):
if self.value:
if data < self.value:
if self.left is None:
self.left = BST(data)
else:
self.left.insert(data)
elif data > self.value:
if self.right is None:
self.right = BST(data)
else:
self.right.insert(data)
else:
self.value = data
def search(self, data):
if self.value==data:
In-order traversal
Code
class BST:
def __init__(self, value):
Questions
1. List and explain Tree terminologies
2. Define tree, binary tree, binary search tree.
3. Explain real time applications of tree.
4. List properties of tree.
5. Demonstrate how data elements are added into the tree.
6. Memory representation of binary tree.
7. Explain a)Insertion b)Search c)Deletion d)Traversal with respect to tree. – algorithm, code,
explanation.
8. Explain different tree traversals.