[LeetCode] Insufficient Nodes in Root to Leaf Paths

1080. Insufficient Nodes in Root to Leaf Paths

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.

A leaf is a node with no children.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
TreeNode* helper(TreeNode* node, int limit, int sum) {
sum += node->val;
bool hasChild = node->left or node->right;

if(!hasChild) return sum < limit ? nullptr : node;

if(node->left) node->left = helper(node->left, limit, sum);
if(node->right) node->right = helper(node->right, limit, sum);

if(hasChild and !(node->left or node->right)) return nullptr;
return node;
}
public:
TreeNode* sufficientSubset(TreeNode* root, int limit) {
return helper(root, limit, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/insufficient-nodes-in-root-to-leaf-paths/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.