Print the nodes having exactly one child in a Binary tree

Given a binary tree, the task is to print all the nodes having exactly one child. Print “-1” if no such node exists.


           / \
          3   5
         /   / \
        7   8   6
Output: 3
There is only one node having
single child that is 3.

          / \
         7   8
            / \
           4   3
Output: -1
There is no node having exactly one
child in the binary tree. 

Approach: The idea is to traverse the tree in the inorder traversal and at each step of the traversal check that if the node is having exactly one child. Then append that node into a result array to keep track of such nodes. After the traversal, simply print each element of this result array.

Below is the implementation of the above approach:






# Python implementation to print
# the nodes having a single child
# Class of the Binary Tree node
class node:
    # Constructor to construct 
    # the node of the Binary tree
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
# List to keep track of 
# nodes having single child
single_child_nodes = []
# Function to find the nodes 
# having single child 
def printNodesOneChild(root):
    # Base Case
    if not root:
    # Condition to check if the node
    # is having only one child
    if not root.left and root.right:
    elif root.left and not root.right:
    # Traversing the left child
    # Traversing the right child
# Driver Code
if __name__ == "__main__":
    # Condtruction of Binary Tree
    root = node(2)
    root.left = node(3)
    root.right = node(5)
    root.left.left = node(7)
    root.right.left = node(8)
    root.right.right = node(6)
    # Function Call
    # Condition to check if there is 
    # no such node having single child
    if not len(single_child_nodes):
        for i in single_child_nodes: 
            print(i.val, end = " ")




Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.