Skip to content

Commit

Permalink
Create Print all nodes that don't have sibling
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored May 6, 2024
1 parent 139277d commit a2c2880
Showing 1 changed file with 125 additions and 0 deletions.
125 changes: 125 additions & 0 deletions Print all nodes that don't have sibling
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//Print all nodes that don't have sibling

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 GfG {
static Node buildTree(String str) {
if(str.length() == 0 || str.charAt(0) == 'N') {
return null;
}

String ip[] = str.split(" ");
Node root = new Node(Integer.parseInt(ip[0]));
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int i = 1;

while(queue.size()>0 && i < ip.length) {
Node currNode = queue.peek();
queue.remove();
String currVal = ip[i];

if(!currVal.equals("N")) {
currNode.left = new Node(Integer.parseInt(currVal));
queue.add(currNode.left);
}
i++;

if(i >= ip.length)
break;

currVal = ip[i];

if(!currVal.equals("N")) {
currNode.right = new Node(Integer.parseInt(currVal));
queue.add(currNode.right);
}
i++;
}

return root;
}

static void printInorder(Node root) {
if(root == null)
return;

printInorder(root.left);
System.out.print(root.data + " ");
printInorder(root.right);
}

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 s = br.readLine();
Node root = buildTree(s);
Tree g = new Tree();
ArrayList<Integer> ans = g.noSibling(root);

for(Integer val : ans)
System.out.print(val + " ");
System.out.println();
}
}
}

class Node {
int data;
Node left, right;

Node(int item) {
data = item;
left = right = null;
}
}

class Tree {
void func(Node root, ArrayList<Integer> ans) {
if(root == null) {
return;
}

if(root.left == null || root.right == null) {
if(root.left != null) {
ans.add(root.left.data);
}

if(root.right != null) {
ans.add(root.right.data);
}
}

func(root.left, ans);
func(root.right, ans);
}

ArrayList<Integer> noSibling(Node node) {
ArrayList<Integer> ans = new ArrayList<>();
func(node, ans);
Collections.sort(ans);

if(ans.size() == 0) {
ans.add(-1);
}

return ans;
}
}

0 comments on commit a2c2880

Please sign in to comment.