Print all nodes that don't have sibling | GeeksforGeeks
Given a Binary Tree, print all nodes that don’t have a sibling (a sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling.
We start from root and check if the node has one child, if yes then print the only child of that node. If node has both children, then recur for both the children
Ask Question: How about root - whether print it?
Read full article from Print all nodes that don't have sibling | GeeksforGeeks
Given a Binary Tree, print all nodes that don’t have a sibling (a sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling.
We start from root and check if the node has one child, if yes then print the only child of that node. If node has both children, then recur for both the children
Ask Question: How about root - whether print it?
void printSingles(struct node *root){ // Base case if (root == NULL) return; // If this is an internal node, recur for left // and right subtrees if (root->left != NULL && root->right != NULL) { printSingles(root->left); printSingles(root->right); } // If left child is NULL and right is not, print right child // and recur for right child else if (root->right != NULL) { cout << root->right->key << " "; printSingles(root->right); } // If right child is NULL and left is not, print left child // and recur for left child else if (root->left != NULL) { cout << root->left->key << " "; printSingles(root->left); }}