Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.
The number of nodes in the tree is in the range [1, 5000].
-105 <= Node.val <= 105
-109 <= limit <= 109
Solutions
Solution 1
Thinking
Nodes that lie only on root-to-leaf paths summing to less than \(\textit{limit}\) must go. A path is decided at the leaf; a parent stays only if a child survives. \(n\le 5000\) allows one postorder.
Descending subtracts the current value from \(\textit{limit}\). A leaf is removed when the remainder is still positive. An internal node is removed only after both children become null.
The call returns the new subtree root, which may be empty.
1 2 3 4 5 6 7 8 9101112131415161718
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defsufficientSubset(self,root:Optional[TreeNode],limit:int)->Optional[TreeNode]:ifrootisNone:returnNonelimit-=root.valifroot.leftisNoneandroot.rightisNone:returnNoneiflimit>0elserootroot.left=self.sufficientSubset(root.left,limit)root.right=self.sufficientSubset(root.right,limit)returnNoneifroot.leftisNoneandroot.rightisNoneelseroot
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcsufficientSubset(root*TreeNode,limitint)*TreeNode{ifroot==nil{returnnil}limit-=root.Valifroot.Left==nil&&root.Right==nil{iflimit>0{returnnil}returnroot}root.Left=sufficientSubset(root.Left,limit)root.Right=sufficientSubset(root.Right,limit)ifroot.Left==nil&&root.Right==nil{returnnil}returnroot}