Iam_Sandeep

Top view of binary tree

Mar 8th, 2022 (edited)
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1.     def topView(self,root):
  2.         ans=deque()
  3.         ans.appendleft(root.data)
  4.         q=deque()
  5.         q.append((root,0))#adding verticle line height in vertical order traversal
  6.         l,r=0,0
  7.         while q:
  8.             t,d=q.popleft()
  9.             if d<l:#if you have found left most vert line then add to left of deque
  10.                 l=d
  11.                 ans.appendleft(t.data)
  12.             if d>r:#if you have found right most vert line then add to right of deque
  13.                 r=d
  14.                 ans.append(t.data)
  15.             if t.left:q.append((t.left,d-1))
  16.             if t.right:q.append((t.right,d+1))
  17.            
  18.         return ans
  19.            
Advertisement
Add Comment
Please, Sign In to add comment