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.
classNode{constructor(val){this.val=val;this.left=null;this.right=null;}}functionbuildTree(indexes){constroot=newNode(1);constmap={1:root};indexes.forEach((val,idx)=>{constid=idx+1;constnode=map[id];if(val[0]>0){node.left=newNode(val[0])map[val[0]]=node.left;}if(val[1]>0){node.right=newNode(val[1])map[val[1]]=node.right;}});returnroot}functioninorderUtil(root,arr){if(!root){return;}inorderUtil(root.left,arr);arr.push(root.val);inorderUtil(root.right,arr)}functiongetInorder(root){constarr=[]inorderUtil(root,arr);returnarr;}functionswapNodes(indexes,queries){// Write your code hereconstroot=buildTree(indexes);constlevelMap={};letlevel=1;constvisit=[root]while(visit.length){constlen=visit.length;levelMap[level]=Array.from(visit);for(leti=0;i<len;i++){constnode=visit.shift();node.left?visit.push(node.left):null;node.right?visit.push(node.right):null;}level++;}constresult=queries.map(q=>{constlevelsToReverse=Object.keys(levelMap).filter(n=>n%q===0);levelsToReverse.forEach(level=>{constnodes=levelMap[level]||[];nodes.forEach((node)=>{lettemp=node.left;node.left=node.right;node.right=temp;})})returngetInorder(root);})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 →
Working Javascript/ JS Solution