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.
There are 4 things that need to happen:
1. Build the tree (from the indexes 2D array), using a variation from BFS/level-order traversal (for loop)
2. Loop through the queries (k) to do the following:
2.1. Swap the nodes at the appropriate level
2.2. Traverse in-order in order to push the values into an array to be returned.
The optimization is that steps 2.1 and 2.2 can be accomplished in a single iteration, resulting in O(n).
JavaScript
classNode{constructor(val){this.val=val;this.levelNum=null;this.left=null;this.right=null;}}/** * Swap nodes in a binary tree at the levels listed in the queries array. * @param {Array<Array<Number>>} indexes * @param {Array<Number>} queries * @returns {Array<Array<Number>>} */functionswapNodes(indexes,queries){if(!indexes?.length||!queries?.length){return[];}elseif(indexes.length===1){returnindexes;}// Construct binary tree from indexes (which is a 2-dimensional array)constroot=newNode(1);root.levelNum=1;constbuildQueue=[root];for(const[leftVal,rightVal]ofindexes){constnode=buildQueue.shift();if(leftVal!==-1){node.left=newNode(leftVal);buildQueue.push(node.left);}if(rightVal!==-1){node.right=newNode(rightVal);buildQueue.push(node.right);}}// `factor` is `k` from the instructionsconstallResults=[];for(constfactorofqueries){constresult=[];traverseInOrderAndSwap(root,factor,result);allResults.push(result);}returnallResults;}/** * Traverse in-order (DFS) and swap the nodes at the appropriate levels. * @param {Node} node * @param {Number} factor * @param {Array<Number>} result */functiontraverseInOrderAndSwap(node,factor,result){constisSwapLevel=node?.levelNum%factor===0;if(isSwapLevel){constholder=node.left;node.left=node.right;node.right=holder;}if(node.left){node.left.levelNum=node.levelNum+1;traverseInOrderAndSwap(node.left,factor,result);}if(node.val)result.push(node.val);if(node.right){node.right.levelNum=node.levelNum+1;traverseInOrderAndSwap(node.right,factor,result);}}
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 →
There are 4 things that need to happen: 1. Build the tree (from the indexes 2D array), using a variation from BFS/level-order traversal (for loop) 2. Loop through the queries (
k
) to do the following: 2.1. Swap the nodes at the appropriate level 2.2. Traverse in-order in order to push the values into an array to be returned.The optimization is that steps 2.1 and 2.2 can be accomplished in a single iteration, resulting in O(n).
JavaScript