Print the left view of binary tree in Python – user input tree

Hello guys, now we are going to print the left view of a binary tree in Python.

Here we are going to use string operations.

Print the left view of a binary tree

n=input("Enter the root:")
p=int(input("Enter the no. of nodes other than root node:"))
r=[]
s=[1]
r.append(n)
for i in range(0,p):
    a=input("Enter the position of node:")
    b=input("Enter the node:")
    q=len(a)
    s.append(q)
    if s[len(s)-1]>s[len(s)-2]:
        r.append(b)
print(*r,sep=" ")

Input:

Enter the root:a
Enter the no. of nodes other than root node:5
Enter the position of node:Rl
Enter the node:b
Enter the position of node:Rr
Enter the node:c
Enter the position of node:Rrl
Enter the node:d
Enter the position of node:Rrr
Enter the node:e
Enter the position of node:Rrlr
Enter the node:f

Output:

a b d

In the above code, you can see that we have taken all inputs from the user. Then we will check for the position of each input and returns if it is on the left side of the tree. So, here we can see that the root node is a, and left view nodes are b and f. Therefore it prints a, b, and d. I hope you enjoyed it.

Leave a Reply

Your email address will not be published. Required fields are marked *