We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
bloc_lst=[]defblocked_list(root):ifrootisNone:returnifroot.left:ifroot.left.right:#print(root.left.right.info,end=" ")bloc_lst.append(root.left.right.info)ifroot.right:ifroot.right.left:#print(root.right.left.info,end=" ")bloc_lst.append(root.right.left.info)blocked_list(root.left)blocked_list(root.right)fromcollectionsimportdefaultdictdeftopView(root):ifnotroot:returnblocked_list(root)blocked_nodes=bloc_lst# Create a dictionary to store nodes at each horizontal distance from the roothd_map=defaultdict(list)# Create a queue for level-order traversalqueue=[(root,0)]#Eachelementisatuple(node,horizontaldistance)whilequeue:node,hd=queue.pop(0)# Check if the node is not blockedifnode.infonotinblocked_nodes:hd_map[hd].append(node.info)ifnode.left:queue.append((node.left,hd-1))ifnode.right:queue.append((node.right,hd+1))# Print the top view nodes in order of horizontal distanceforhdinsorted(hd_map):print(hd_map[hd][0],end=" ")
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree : Top View
You are viewing a single comment's thread. Return to all comments →