A
/ \
B C
/ \ / \
D E F G
Здесь N = общее число. узлов в дереве = 7
(длина пути листового узла берется как ноль.)
Acc. к рекурсивному определению:
Path length of tree = Path length with Root A
= Path length with Root B + Path length with Root C + (7-1)
= (Path length with Root D + Path length with Root E + (3-1))
+ (Path length with Root F + Path length with Root G + (3-1))
+ (7-1)
= ((0 + 0 + 2) + (0 + 0 + 2)) + 6
= 10
Его реализация может быть следующей:
int Recurse(Node root, int totalNodes)
{
if (totalNodes == 1)
return 0;
int noOfNodes1 = CountNodes(root.left);
int noOfNodes2 = CountNodes(root.right);
return ( Recurse(root.left, noOfNodes1)
+ Recurse(root.right, noOfNodes2) + totalNodes - 1);
}