Insufficient Nodes in Root to Leaf Paths in Python

When working with binary trees, we sometimes need to remove nodes based on path sum criteria. A node is insufficient if every root-to-leaf path passing through that node has a sum strictly less than a given limit. This problem requires us to delete all insufficient nodes simultaneously and return the modified tree.

Problem Understanding

Given a binary tree and a limit value, we need to identify and remove nodes where all paths from root to leaf through that node have sums less than the limit. The key insight is that we work backwards from leaves, checking if any path through a node meets the threshold ?

Original Tree (limit = 1) 1 2 3 -5 4 Path 1?2?(-5) = -2 < 1 Path 1?3?4 = 8 ? 1 After Removal 1 3 4 Node 2 and -5 removed

Algorithm Approach

We use a recursive approach that works from leaves up to the root. For each node, we:

  • Check if it's a leaf node and compare its value with the remaining limit
  • Recursively process left and right subtrees with updated limit
  • Remove the current node if all its children are removed

Implementation

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def sufficientSubset(self, root, limit):
        """
        Remove insufficient nodes from binary tree
        :param root: TreeNode - root of binary tree
        :param limit: int - minimum required path sum
        :return: TreeNode - root of modified tree
        """
        # Base case: if node is a leaf
        if not root.left and not root.right:
            # Remove leaf if its value is less than remaining limit
            return None if root.val < limit else root
        
        # Process left subtree if exists
        if root.left:
            root.left = self.sufficientSubset(root.left, limit - root.val)
        
        # Process right subtree if exists  
        if root.right:
            root.right = self.sufficientSubset(root.right, limit - root.val)
        
        # Remove current node if both children are removed
        return root if root.left or root.right else None

# Example usage
def build_tree():
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(-5)
    root.right.right = TreeNode(4)
    return root

def print_tree(root, level=0):
    if root:
        print_tree(root.right, level + 1)
        print('  ' * level + str(root.val))
        print_tree(root.left, level + 1)

solution = Solution()
tree = build_tree()
print("Original tree:")
print_tree(tree)

result = solution.sufficientSubset(tree, 1)
print("\nAfter removing insufficient nodes:")
print_tree(result)

How It Works

The algorithm works by:

  1. Leaf Check: When we reach a leaf node, we compare its value directly with the remaining limit
  2. Recursive Processing: For internal nodes, we recursively process children with the updated limit (limit - current_node_value)
  3. Node Removal: A node is removed if all its children are removed, indicating no valid path exists through it
  4. Path Sum Tracking: The limit is reduced at each level, effectively tracking the remaining sum needed

Time and Space Complexity

Aspect Complexity Explanation
Time O(n) Visit each node once
Space O(h) Recursion depth equals tree height

Conclusion

This solution efficiently removes insufficient nodes by using post-order traversal and tracking path sums. The key insight is processing children before deciding whether to keep the current node, ensuring all insufficient paths are eliminated.

Updated on: 2026-03-25T08:15:07+05:30

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements