Print all nodes that don 't have sibling | A binary tree node ; Function to print all non - root nodes that don 't have a sibling ; Base case ; If this is an internal node , recur for left and right subtrees ; If left child is NULL and right is not , print right child and recur for right child ; If right child is NULL and left is not , print left child and recur for left child ; Driver program to test the above functions ; Let us construct the tree shown in above diagram
class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void printSingles ( Node node ) { if ( node == null ) return ; if ( node . left != null && node . right != null ) { printSingles ( node . left ) ; printSingles ( node . right ) ; } else if ( node . right != null ) { System . out . print ( node . right . data + " ▁ " ) ; printSingles ( node . right ) ; } else if ( node . left != null ) { System . out . print ( node . left . data + " ▁ " ) ; printSingles ( node . left ) ; } } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . right = new Node ( 4 ) ; tree . root . right . left = new Node ( 5 ) ; tree . root . right . left . right = new Node ( 6 ) ; tree . printSingles ( tree . root ) ; } }