20(July) Remove Half Nodes
20. Remove Half Nodes
The problem can be found at the following link: Question Link
Problem Description
You are given a binary tree, and you need to remove all the half nodes (nodes with only one child). Return the root node of the modified tree after removing all the half nodes.
Example:
Input:
tree = 5
/ \
7 8
/
2Output:
2 5 8Explanation: In the above tree, the node 7 has only a single child. After removing the node, the tree becomes 2<-5->8. Hence, the answer is 2 5 8 in inorder traversal.
My Approach
Base Case:
If the current node is
nullptr, returnnullptr.
Recursive Case:
Recursively call
RemoveHalfNodeson the left and right children.Update the left and right children of the current node with the results from the recursive calls.
Removal of Half Nodes:
If the current node is a half node (only one child is
nullptr), return the non-null child after deleting the current node.If the current node has both children or no children, return the current node itself.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we traverse each node once in the binary tree.
Expected Auxiliary Space Complexity: O(h), where h is the height of the binary tree, due to the recursive call stack.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated