You are given a binary tree. Picture each node as a comment in a thread: its value is the comment's vote count and its children (at most two) are replies to it. Given the root of the tree and a target node value, compute aggregated metrics for the node holding that value.
Return a list of three integers [total_votes, total_descendants, direct_children] where:
-
total_votes
is the sum of all node values in the subtree rooted at the target node, including the target node itself.
-
total_descendants
is the number of nodes in that subtree, not counting the target node itself.
-
direct_children
is the number of immediate children of the target node (0, 1 or 2).
If no node has the value target, return [-1, -1, -1]. All node values are unique.
Function Signature
class TreeNode:
def __init__(self, val: int = 0, left: "TreeNode | None" = None, right: "TreeNode | None" = None):
self.val = val
self.left = left
self.right = right
def tree_report(root: TreeNode | None, target: int) -> list[int]:
...
Rules
-
The examples write the tree in level order, with
null
marking a missing child. Children of a missing node are not listed.
-
Values are unique, so at most one node matches
target
.
Constraints
-
1 <= number of nodes <= 10^4
-
0 <= Node.val <= 10^5
-
All node values are unique.
-
0 <= target <= 10^5
Examples
Input: root = [10,5,15,3,7,null,20], target = 5
Output: [15,2,2]
The tree has 10 at the root, 5 and 15 as its children, 3 and 7 under 5, and 20 as the right child of 15. The subtree at 5 holds 5, 3 and 7, so the vote total is 5 + 3 + 7 = 15, there are 2 descendants, and 5 has 2 direct children.
Input: root = [10,5,15,3,7,null,20], target = 15
Output: [35,1,1]
The subtree at 15 holds 15 and 20, so the total is 35. Node 20 is the only descendant, and 15 has only a right child.
Input: root = [10,5,15,3,7,null,20], target = 8
Output: [-1,-1,-1]
No node has the value 8.