Skip to content

Commit

Permalink
Update KDistanceFromRoot.java
Browse files Browse the repository at this point in the history
  • Loading branch information
SOHAMmondal2003 authored Oct 12, 2022
1 parent 3e6e17b commit 0f906d8
Showing 1 changed file with 134 additions and 0 deletions.
134 changes: 134 additions & 0 deletions Tree/KDistanceFromRoot.java
Original file line number Diff line number Diff line change
@@ -1 +1,135 @@


import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
import java.util.*;

class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left=null;
right=null;
}
}

class KDistanceFromRoot {

static Node buildTree(String str){

if(str.length()==0 || str.charAt(0)=='N'){
return null;
}

String ip[] = str.split(" ");
// Create the root of the tree
Node root = new Node(Integer.parseInt(ip[0]));
// Push the root to the queue

Queue<Node> queue = new LinkedList<>();

queue.add(root);
// Starting from the second element

int i = 1;
while(queue.size()>0 && i < ip.length) {

// Get and remove the front of the queue
Node currNode = queue.peek();
queue.remove();

// Get the current node's value from the string
String currVal = ip[i];

// If the left child is not null
if(!currVal.equals("N")) {

// Create the left child for the current node
currNode.left = new Node(Integer.parseInt(currVal));
// Push it to the queue
queue.add(currNode.left);
}

// For the right child
i++;
if(i >= ip.length)
break;

currVal = ip[i];

// If the right child is not null
if(!currVal.equals("N")) {

// Create the right child for the current node
currNode.right = new Node(Integer.parseInt(currVal));

// Push it to the queue
queue.add(currNode.right);
}
i++;
}

return root;
}

public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int t=Integer.parseInt(br.readLine());

while(t > 0){
String X[] = br.readLine().trim().split(" ");
int k = Integer.parseInt(X[0]);
String s = br.readLine();
Node root = buildTree(s);
Tree g = new Tree();
ArrayList<Integer> nodes = g.Kdistance(root,k);
for(int i = 0;i<nodes.size();i++){
System.out.print(nodes.get(i)+ " ");
}
System.out.println();
t--;

}
}

}




class Tree{
class pair{
Node node;
int level;
pair(Node node, int level){
this.node = node;
this.level = level;
}
}


ArrayList<Integer> Kdistance(Node root, int k){
Queue<pair> PQ = new LinkedList<>();
PQ.add(new pair(root, 0));

ArrayList<Integer> adj = new ArrayList<>();

while(!PQ.isEmpty()){
pair curr = PQ.poll();
if(curr.level == k) {
adj.add(curr.node.data);
}

if(curr.level > k) break;

if(curr.node.left != null) PQ.add(new pair(curr.node.left, curr.level+1));
if(curr.node.right != null) PQ.add(new pair(curr.node.right, curr.level+1));
}

return adj;
}
}

0 comments on commit 0f906d8

Please sign in to comment.