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.
#!/bin/python3importmathimportosimportrandomimportreimportsysfromcollectionsimportdeque## 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## very compact when to depict a tree# use a list (or dic) of the nodes to represent the tree# the ith node on the tree has the data of i+1# so as long as you can find a node that is not -1 then you can find it child and kkep on sys.setrecursionlimit(2000)# get the inorder from the i in treedefinOrder(i,tree):# nothing to further checkifi==-1:return[]# get two sons for this non null node# note, its sons are in the i-1 positionleft,right=tree[i-1]returninOrder(left,tree)+[i]+inOrder(right,tree)# make a list of list to track the depth (use the deque)# 0: [1], 1:[2,3], can cause a blank list defgetNodeDeepth(tree):depth_list=[[1]]# the initial queuedepth_queue=deque([1])# those are in the same depthwhiledepth_queue:# we are dealing a new depth of nodedepth_list.append([])for_inrange(len(depth_queue)):i=depth_queue.popleft()l,r=tree[i-1]ifl!=-1:depth_queue.append(l)depth_list[-1].append(l)ifr!=-1:depth_queue.append(r)depth_list[-1].append(r)ifnotdepth_list[-1]:depth_list.pop()returndepth_listdefswapNodes(indexes,queries):#print(inOrder(1,indexes))depth_list=getNodeDeepth(indexes)ret=[]forkinqueries:i=1whilei*k<=len(depth_list):parents=depth_list[i*k-1]forpinparents:l,r=indexes[p-1]indexes[p-1]=r,li+=1ret.append(inOrder(1,indexes))returnret# Write your code hereif__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')n=int(input().strip())indexes=[]for_inrange(n):indexes.append(list(map(int,input().rstrip().split())))queries_count=int(input().strip())queries=[]for_inrange(queries_count):queries_item=int(input().strip())queries.append(queries_item)result=swapNodes(indexes,queries)fptr.write('\n'.join([' '.join(map(str,x))forxinresult]))fptr.write('\n')fptr.close()
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 →