Counting Nodes in a Tree Recursively

A tree can be counted by adding each node to the sizes of all its child subtrees. An empty subtree contributes zero.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an uneven tree
  2. Check the representation assumption
  3. Count internal nodes as well as descendants
  4. Check what the tree assumption buys

Trace an uneven tree

Take a root with a leaf on the left and a right child that has one child of its own. The subtree counts are one and two. The root raises the total to four. Each nested call reports the same kind of result under its function contract.

Check the representation assumption

If two references lead to the same node in a shared graph, recursively counting both paths can count it twice. Use a visited set when the task counts distinct reachable objects.[1]

Count internal nodes as well as descendants

Let A have children B and C, and let C have child D. Begin with a contribution of one for each visited node. The result for C is two, since it contributes one and D contributes one. The root total is four. See counting costs by input size for how the chosen unit relates to this sum.

Node  Children    Size
B     []          1
D     []          1
C     [D]         2
A     [B, C]      4

Check what the tree assumption buys

Distinct child subtrees have no shared nodes in a tree. If both B and C referenced D in a graph, the same recursive rule could count D twice. For a count of distinct reachable nodes, carry a visited set and test a diamond and a cycle.

References

  1. Jeff Erickson, Algorithms ↩