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
- Product of all nodes in a Binary Tree
- Sum of nodes in top view of binary tree
- Sum of all the Boundary Nodes of a Binary Tree
- Sink Odd nodes in Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Sum of all leaf nodes of binary tree
- Print nodes in top view of Binary Tree | Set 2
- Find maximum among all right nodes in Binary Tree
- Print all even nodes of Binary Search Tree
- Print all internal nodes of a Binary tree
- Print Levels of all nodes in a Binary Tree
- Product of all leaf nodes of binary tree
Improved By : shrikanth13