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.
- Sort first half in ascending and second half in descending order | 1
- Print all nodes in a binary tree having K leaves
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Difference between sums of odd level and even level nodes of a Binary Tree
- Find distance between two nodes of a Binary Tree
- Check if two nodes are cousins in a Binary Tree
- Print Nodes in Top View of Binary Tree
- Print leftmost and rightmost nodes of a Binary Tree
- Print extreme nodes of each level of Binary Tree in alternate order
- Find height of a special binary tree whose leaf nodes are connected
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Given a linked list which is sorted, how will you insert in sorted way
- Given a binary tree, print all root-to-leaf paths
- Find sum of all left leaves in a given Binary Tree
- Delete N nodes after M nodes of a linked list
- Convert a Binary Tree into its Mirror Tree
- Print all nodes at distance k from a given node
- Print all nodes at distance K from given node: Iterative Approach
Improved By : shrikanth13