diff --git a/Print all nodes that don't have sibling b/Print all nodes that don't have sibling new file mode 100644 index 0000000..417b058 --- /dev/null +++ b/Print all nodes that don't have sibling @@ -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 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 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 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 noSibling(Node node) { + ArrayList ans = new ArrayList<>(); + func(node, ans); + Collections.sort(ans); + + if(ans.size() == 0) { + ans.add(-1); + } + + return ans; + } +}