Skip to content

Commit ac46a68

Browse files
Tree Traversal,Verticalorder,topview
1 parent c822103 commit ac46a68

File tree

6 files changed

+342
-31
lines changed

6 files changed

+342
-31
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
def display(head):
1+
def inorder(head):
22
if head:
3-
display(head.left)
3+
inorder(head.left)
44
print(head.data)
5-
display(head.right)
5+
inorder(head.right)
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
def postorder(head):
22
if head:
3-
display(head.left)
4-
display(head.right)
3+
postorder(head.left)
4+
postorder(head.right)
55
print(head.data)
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
def preorder(head):
22
if head:
33
print(head.data)
4-
display(head.left)
5-
display(head.right)
4+
preorder(head.left)
5+
preorder(head.right)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# https://www.hackerrank.com/challenges/tree-top-view/problem
2+
def topView(root):
3+
def fun(node, depth, pos):
4+
if node is None:
5+
return
6+
fun(node.left, depth+1, pos-1)
7+
fun(node.right, depth+1, pos+1)
8+
if (pos in ans and depth<ans[pos][0]) or pos not in ans:
9+
ans[pos] = (depth,node)
10+
11+
ans = {}
12+
fun(root,0,0)
13+
keys = sorted(ans.keys())
14+
for key in keys:
15+
print(ans[key][1].data, end = ' ')
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def vertical(head,hd,m):
2+
if head is None:
3+
return
4+
if hd not in m:
5+
m[hd]=head.data
6+
vertical(head.left,hd-1,m)
7+
vertical(head.right,hd+1,m)
8+
m=dict()
9+
hd=0
10+
vertical(root,hd,m)
11+
for i in sorted(m):
12+
print(m[i][0])

0 commit comments

Comments
 (0)