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.
fromcollectionsimportdequesys.setrecursionlimit(500000)## Complete the 'swapNodes' function below.## The function is expected to return a 2D_INTEGER_ARRAY.# The function accepts following parameters:# 1. 2D_INTEGER_ARRAY indexes# 2. INTEGER_ARRAY queries#classnode:def__init__(self,info,depth):self.info=infoself.depth=depthself.left=Noneself.right=NonedefcreateTree(indexes):q=deque()root=node(1,1)q.append(root)forxinindexes:ele=q.popleft()ifx[0]!=-1:ele.left=node(x[0],ele.depth+1)q.append(ele.left)ifx[1]!=-1:ele.right=node(x[1],ele.depth+1)q.append(ele.right)iflen(q)==0:breakreturnrootdefinorder(root):values=[]definorder_traversal(root):ifrootisNone:returninorder_traversal(root.left)values.append(root.info)inorder_traversal(root.right)inorder_traversal(root)returnvaluesdefnodesStack(root):stack=[root]values=[]whilelen(stack)!=0:ele=stack.pop()values.append(ele)ifele.left:stack.append(ele.left)ifele.right:stack.append(ele.right)returnvaluesdefswapNodes(indexes,queries):# Write your code hereroot=createTree(indexes)nodes=nodesStack(root)finalarray=[]forkinqueries:forninnodes:ifn.depth%k==0:ifn.leftisNoneandn.rightisNone:passelifn.leftisNoneandn.right:n.left=n.rightn.right=Noneelifn.rightisNoneandn.left:n.right=n.leftn.left=Noneelse:temp=n.rightn.right=n.leftn.left=tempfinalarray.append(inorder(root))returnfinalarray
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 →