1080. Insufficient Nodes in Root to Leaf Paths

1080. Insufficient Nodes in Root to Leaf Paths

Description

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.

Example 1:

1
2
Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
Output: [1,2,3,4,null,null,7,8,9,null,14]

Example 2:

1
2
Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
Output: [5,4,8,11,null,17,4,7,null,null,null,5]

Example 3:

1
2
Input: root = [1,2,-3,-5,null,4,null], limit = -1
Output: [1,null,-3,4]

Constraints:

  • The number of nodes in the tree is in the range [1, 5000].
  • -10^5 <= Node.val <= 10^5
  • -10^9 <= limit <= 10^9

Hints/Notes

  • binary tree

Solution

Language: C++

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
30
31
32
33
34
/**
* 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 {
public:
TreeNode* sufficientSubset(TreeNode* root, int limit) {
if (!root) {
return root;
}

if (!root->left && !root->right) {
if (root->val < limit) {
return nullptr;
}
return root;
}

root->left = sufficientSubset(root->left, limit - root->val);
root->right = sufficientSubset(root->right, limit - root->val);

if (!root->left && !root->right) {
return nullptr;
}
return root;
}
};