Final answer:
An algorithm to find the number of descendants of each node in a binary tree can be implemented using a depth-first search approach.
Step-by-step explanation:
An algorithm to find the number of descendants of each node in a binary tree can be implemented using a depth-first search approach.
- Start with the root node and initialize a counter for each node's descendants.
- Recursively traverse the left and right subtrees. For each node encountered, increment its counter by adding the descendants of its left and right children.
- Repeat this process until all nodes have been visited.
- At the end, the counters will hold the number of descendants for each node in the binary tree.
For example, consider the binary tree:
1
/
2 3
/ \
4 5 6
The algorithm would yield the following counts:
Node 1: 5 descendants
Node 2: 2 descendants
Node 3: 1 descendant
Node 4: 0 descendants
Node 5: 0 descendants
Node 6: 0 descendants