Insufficient Nodes in Root to Leaf Paths LeetCode solution in C++

1
// What we do is a basic DFS from root to leaf, here I used preorder.
2
class Solution {
3
public:
4
TreeNode *sufficientSubset(TreeNode *root, int limit) {
5
// Base cases to check if there is no root node
6
if (!root) return root;
7
// or else if there are no leaf nodes to the root node and thus we simply
8
// check if the root node is less than the limit or not, if it is less we
9
// return null or else we know what to return.
10
if (!root->left && !root->right) {
11
if (root->val < limit)
12
return NULL;
13
else
14
return root;
15
} else {
16
// We then start out DFS traversal, every time decreasing the limit with
17
// the current node's value and after that, we move over ahead and check
18
// the base conditions again and see if any case has been satisfied or not
19
root->left = sufficientSubset(root->left, limit - root->val);
20
root->right = sufficientSubset(root->right, limit - root->val);
21

22
if (!root->left && !root->right)
23
return NULL;
24
else
25
return root;
26
}
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0