Conditional Travel Package Value
MakeMyTrip offers complex travel packages which can be represented as hierarchical structures (binary trees). Each node in this tree represents a component of the package with an associated value (e.g., cost, profit, rating). To optimize package offerings, we need to calculate the total value of a package, but with a specific business rule: certain "negative impact" components might invalidate their sub-components if they appear consecutively.
Implement a function calculateConditionalPackageValue that takes the root of a binary tree as input. The function should traverse the tree and calculate the sum of values of all nodes that are part of a 'valid' path from the root. A path is considered 'valid' for a node if its value is included based on the following rules:
root: TreeNode | null - The root of a binary tree. Each TreeNode has an integer val.number - The total sum of values of all valid nodes in the tree according to the rules.null) should result in a total sum of 0.Examples
Example 1
Input:
root = [10,5,-3,-2,7,null,11]
Output:
28
Note:
The tree is:
10
/
5 -3
/ \
-2 7 11
Example 2
Input:
root = [1,-5,2,-3,-4,null,6]
Output:
4
Note:
The tree is:
1
/
-5 2
/ \
-3 -4 6
Example 3
Input:
root = [-10]
Output:
-10
Note:
The tree consists only of the root node -10. The root node always contributes its value, so the sum is -10.
Constraints
0 and 10^4.val) will be between -1000 and 1000.Loading editor...