Print all nodes that don 't have sibling | Program to find singles in a given binary tree ; 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 above functions ; Let us create binary tree given in the above example
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { struct node * left , * right ; int key ; } ; node * newNode ( int key ) { node * temp = new node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } void printSingles ( struct node * root ) { if ( root == NULL ) return ; if ( root -> left != NULL && root -> right != NULL ) { printSingles ( root -> left ) ; printSingles ( root -> right ) ; } else if ( root -> right != NULL ) { cout << root -> right -> key << " ▁ " ; printSingles ( root -> right ) ; } else if ( root -> left != NULL ) { cout << root -> left -> key << " ▁ " ; printSingles ( root -> left ) ; } } int main ( ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> left -> left = newNode ( 6 ) ; printSingles ( root ) ; return 0 ; }