Given A binary Tree, how do you remove all the half nodes (which has only one child)? Note leaves should not be touched as they have both children as NULL.
For example consider the below tree.
Nodes 2 and 4 are half nodes as one of their child is Null.
The idea is to use post-order traversal to solve this problem efficiently. We first process the left children, then right children, and finally the node itself. So we form the new tree bottom up, starting from the leaves towards the root. By the time we process the current node, both its left and right subtrees were already processed. Below is the implementation of this idea.
Inorder traversal of given tree 7 1 6 11 2 5 4 9 Inorder traversal of the modified tree 1 6 11 2 4
Time complexity of the above solution is O(n) as it does a simple traversal of binary tree.
This article is contributed by Jyoti Saini. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Count half nodes in a Binary tree (Iterative and Recursive)
- Remove all multiples of K from Binary Tree
- Sum of all nodes in a binary tree
- Sum of nodes in top view of binary tree
- Sink Odd nodes in Binary Tree
- Sum of all leaf nodes of binary tree
- Sum of all the Boundary Nodes of a Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Product of all nodes in a Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Check if two nodes are cousins in a Binary Tree
- Sum of heights of all individual nodes in a binary tree
- Find distance between two nodes of a Binary Tree
- Print path between any two nodes in a Binary Tree
- Print all nodes between two given levels in Binary Tree
Improved By : shrikanth13