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.
privatestaticNodecreateTree(Noderoot,List<List<Integer>>indexes){Queue<Node>queue=newArrayDeque<>();queue.add(root);inti=0;while(!queue.isEmpty()&&(i<indexes.size())){List<Integer>index=indexes.get(i++);Noden=queue.remove();if(index.get(0)>1){n.left=newNode(index.get(0));queue.add(n.left);}if(index.get(1)>1){n.right=newNode(index.get(1));queue.add(n.right);}}returnroot;}privatestaticvoidinOrder(Noderoot,List<Integer>indexes){if(root==null)return;inOrder(root.left,indexes);indexes.add(root.data);inOrder(root.right,indexes);}privatestaticvoidswap(Noderoot,intlevel,intquery){if((root==null)||root.left==root.right)return;if((level%query)==0){Nodea=root.left;root.left=root.right;root.right=a;}swap(root.left,level+1,query);swap(root.right,level+1,query);}publicstaticList<List<Integer>>swapNodes(List<List<Integer>>indexes,List<Integer>queries){// Write your code hereList<List<Integer>>result=newArrayList<>();Noderoot=newNode(1);createTree(root,indexes);for(Integerq:queries){List<Integer>list=newArrayList<>();swap(root,1,q);inOrder(root,list);result.add(list);}returnresult;}
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 →
Java: