-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathLeftViewOfATree.py
65 lines (56 loc) · 1.59 KB
/
LeftViewOfATree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
@author Anirudh Sharma
Given a Binary Tree, print Left view of it.
Left view of a Binary Tree is set of nodes visible when tree is visited from Left side.
"""
def leftView(root):
# list to store the result
result = []
# Special case
if root is None:
return result
# Queue to store the nodes of the tree
nodes = []
# Add the root node in the queue
nodes.append(root)
# Loop until the queue is empty
while nodes:
# Get the size of the queue
size = len(nodes)
# Loop until the size
for i in range(size):
# Get the current node
current = nodes.pop(0)
# If it is the first node at the current level,
# add it to the result
if i == 0:
result.append(current.data)
# Move to left child if exists
if current.left:
nodes.append(current.left)
# Move to right child if exists
if current.right:
nodes.append(current.right)
return result
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
if __name__ == "__main__":
root = Node(1)
root.left = Node(3)
root.right = Node(2)
print(leftView(root))
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.left.right = Node(60)
print(leftView(root))
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(leftView(root))