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 the Boundary Nodes of a Binary Tree
- Sum of nodes in the right view of the given binary tree
- Sum of all leaf nodes of binary tree
- Product of all nodes in a Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Sink even nodes in Binary Tree
- Print all even nodes of Binary Search Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Maximum sum of nodes in Binary tree such that no two are adjacent
- Sum of heights of all individual nodes in a binary tree
Improved By : shrikanth13