【发布时间】:2011-08-19 06:03:19
【问题描述】:
计算树中节点数的函数。
int count(node *t)
{
int i;
if (t == NULL)
return(0);
i = 1 + count(t->left) + count(t->right); // recursion occurs address of left node is passed and
return(i); // continue to pass until whole left node
} // is traversed and the value of t is
// NULL and 0 is returned same for right node counting
// i = 1 + 0 + 0 = 1
节点数是怎么统计的?
【问题讨论】:
-
左节点是子树。右节点也是一个子树。函数正在调用自身,子树作为参数并且计数递增。现在,当计数器到达叶子时,它没有任何子节点,所以它返回 0。意思是
leaf tree has count one。现在它上升了一级,结果是1 + left leaf count + right leaf count) = 3。同样,它又上一级并获得总数。 假设所有节点除了叶子之外都有左右子节点。嗯,概念不变