Tree Value Count

Tree Value Count

Return how many nodes in the tree hold a given target value.

treeValueCount(root, target)

Input format: tree | target.

Examples

(1 4 4 x x 4 1), 4   // → 3
(1 2 3), 9           // → 0
(empty), 0           // → 0

Walkthrough

Thinking it through

This is a counting variant of the same recursive shape as "count all nodes" or "sum all values": instead of every node contributing automatically, each contributes conditionally — 1 if it matches the target, 0 otherwise.

The local question

For any node: how many matches live in the subtree rooted here? That's this node's own contribution (0 or 1) plus matches in the left subtree plus matches in the right — every node in the subtree is one of those three places, no overlap, no gaps.

The base case

An empty subtree has zero matches — the same neutral base case as counting or summing.

Why you can't stop early the way you could for tree-includes

A plain existence check can stop the moment it finds one match. Here, finding one match doesn't tell you whether others exist elsewhere — the target could appear multiple times, so you can't short-circuit. Every node genuinely has to be checked.

Why this doesn't need the tree to have any special structure

Like tree-min-value, this works regardless of any ordering rules, since a value match has nothing to do with ordering. Structurally, it's the same problem as tree-sum with a different per-node rule: "add 1 if I match, else 0" instead of "add my own value." A whole family of tree problems — count, sum, count-matches, find max/min — share this identical skeleton, only the per-node rule changes.

Cost

Every node must be visited once, so work is proportional to the number of nodes, with recursion memory bounded by the tree's height.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.