Recursion and tree traversal

Count all nodes in each tree. A missing child contributes zero.

Examples

Example 1

Input
Root R has children A and B. B has child C.
Expected output
4

Example 2

Input
No root node
Expected output
0

Hints and solution

Hint 1

Compute the count returned by each child before combining it at the root.

Reveal worked answer

A leaf returns one because both of its children are missing. A root with a two-node subtree and a one-node subtree returns 1 + 2 + 1, or four.

Back to the lesson