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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- If you are given two traversal sequences, can you construct the binary tree?
- Count half nodes in a Binary tree (Iterative and Recursive)
- Sort first half in ascending and second half in descending order | 1
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Count of all prime weight nodes between given nodes in the given Tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Find sum of all nodes of the given perfect binary tree
- Print all nodes between two given levels in Binary Tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Check whether a given binary tree is skewed binary tree or not?
- Remove all multiples of K from Binary Tree
- Sum of all odd nodes in the path connecting two given nodes
- Print all nodes in a binary tree having K leaves
- Print all full nodes in a Binary Tree
Improved By : shrikanth13