Given a binary tree, the task is to print all the nodes having exactly one child. Print “-1” if no such node exists.
Input: 2 / \ 3 5 / / \ 7 8 6 Output: 3 Explanation: There is only one node having single child that is 3. Input: 9 / \ 7 8 / \ 4 3 Output: -1 Explanation: 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:
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.
- Sum of all the child nodes with even grandparents in a Binary Tree
- Sum of all the child nodes with even parent values in a Binary Tree
- Count of nodes in a Binary Tree whose child is its prime factors
- Print all internal nodes of a Binary tree
- Print path between any two nodes in a Binary Tree
- Print all full nodes in a Binary Tree
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print all nodes between two given levels in Binary Tree
- Print Levels of all nodes in a Binary Tree
- Print all nodes in a binary tree having K leaves
- Print nodes in the Top View of Binary Tree | Set 3
- Print all even nodes of Binary Search Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print nodes between two given level numbers of a binary tree
- Print leftmost and rightmost nodes of a Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Print all leaf nodes of a Binary Tree from left to right
- Print all leaf nodes of a binary tree from right to left
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.