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.
Here it is in java:
int numberOfNodes = indexes.length;
int numOfQueries= queries.length;
int[][] result =new int[numOfQueries][numberOfNodes];
Node root = new Node(1,1);
Node curr = root;
Queue<Node> nodes = new LinkedList<>();
nodes.offer(curr);
//tree creation
int N = 0;
while (N<numberOfNodes)
{
curr =nodes.poll();
int leftNode = indexes[N][0];
int rightNode = indexes[N][1];
curr.left = leftNode == -1?null:new Node(leftNode,curr.depth+1);
curr.right = rightNode == -1?null:new Node(rightNode,curr.depth+1);
//Now we are going to add the nodes for next iteration to create node
if (curr.left!=null && curr.left.data != -1)
nodes.offer(curr.left);
if(curr.right!=null && curr.right.data != -1)
nodes.offer(curr.right);
N++;
}//loop over
}
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 →