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.
pythonfromcollectionsimportdequeclassNode():def__init__(self,val):self.val=valself.left=Noneself.right=NonedefcreateNodeFromIndexes(indexes):ifnotindexes:returnNoneroot=Node(1)dq=deque([root])ind=0whiledqandind<len(indexes):node=dq.popleft()left_val,right_val=indexes[ind]ifleft_val!=-1:node.left=Node(left_val)dq.append(node.left)ifright_val!=-1:node.right=Node(right_val)dq.append(node.right)ind+=1returnrootdefswapAtHeightMultiples(root,query):dq=deque([root])currH=1whiledq:length=len(dq)for_inrange(length):node=dq.popleft()ifcurrH%query==0:node.left,node.right=node.right,node.leftifnode.left:dq.append(node.left)ifnode.right:dq.append(node.right)currH+=1returnrootdefinOrderTraversalList(root):ifnotroot:return[]ans=[]stack=[]current=rootwhilestackorcurrent:whilecurrent:stack.append(current)current=current.leftcurrent=stack.pop()ans.append(current.val)current=current.rightreturnansdefswapNodes(indexes,queries):# Write your code hereroot=createNodeFromIndexes(indexes)ans=[]forqueryinqueries:root=swapAtHeightMultiples(root,query)e=inOrderTraversalList(root)ans.append(e)returnans
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Swap Nodes [Algo]
You are viewing a single comment's thread. Return to all comments →
Python 3 solution