CC Ex6

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Experiment - 6 (Trees)

Student Name: Adarsh Kesharwani UID: 20BCS7731


Branch: CSE Section/Group: 610-B
Semester: 5th
Subject Code: 20CSP-314

1.1 Aim: Tree Top View.


Given a pointer to the root of a binary tree, print the top view of the binary tree.
The tree as seen from the top the nodes, is called the top view of the tree.

1.2 Input:
6
125364
1.3 Sample Output:
1256

1.3 Code:
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root == None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.info:
if current.left:
current = current.left
else:
current.left = Node(val)

break
elif val > current.info:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
def topView(root):
if(root == None):
return
q = []
m = dict()
level = 0
root.level = level
q.append(root)
while(len(q)):
root = q[0]
level = root.level
if level not in m:
m[level] = root.info
if(root.left):
root.left.level = level - 1
q.append(root.left)
if(root.right):
root.right.level = level + 1
q.append(root.right)
q.pop(0)
for i in sorted(m):
print(m[i], end=" ")
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.create(arr[i])
topView(tree.root)

1.5 Output:

2.1 Aim: Binary Search Tree: Insertion.


2.2 Sample Input:
6
423176
2.3 Sample Output:
421376
2.4 Code:
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None

def __str__(self):
return str(self.info)

def preOrder(root):
if root == None:
return
print (root.info, end=" ")
preOrder(root.left)
preOrder(root.right)

class BinarySearchTree:
def __init__(self):
self.root = None

def insert(self, info):


if self.root is None:

self.root = Node(info)
else:
node = self.root
while(True):
if (node.info>info):
if node.left:
node = node.left
else:
node.left = Node(info)
return
else:
if node.right:
node = node.right
else:
node.right = Node(info)
return

tree = BinarySearchTree()
t = int(input())

arr = list(map(int, input().split()))


for i in range(t):
tree.insert(arr[i])

preOrder(tree.root)

2.5 Output:

You might also like