Count Parent Nodes With a Target Sum
Problem statement
A binary tree is serialized in preorder as one comma-separated string preorder. Each non-null node is written as its signed integer value, and each missing child is written as #.
A parent node qualifies only when it has both a left child and a right child. Count the qualifying parent nodes whose own value plus the values of their two direct children equals target.
Return the total number of qualifying parent nodes.
Function
countTargetParents(preorder: String, target: long) → intExamples
Example 1
preorder = "5,3,#,#,2,#,#"target = 10return = 1The root has direct children 3 and 2, and 5 + 3 + 2 = 10. The leaves are not parent nodes.
Example 2
preorder = "1,2,4,#,#,5,#,#,3,#,6,#,#"target = 11return = 1Node 2 has children 4 and 5, so it qualifies because 2 + 4 + 5 = 11. Node 3 has only one child and does not qualify.
Constraints
- The serialization describes one valid, non-empty binary tree.
1 <= number of non-null nodes <= 2000-10^9 <= node value <= 10^9-3 * 10^9 <= target <= 3 * 10^9- Tokens are separated by commas and may contain surrounding spaces.