该函数如何计算树中的节点数?

时间:2011-05-05 10:08:59

标签: c recursion tree

计算树中节点数的函数。

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

如何计算节点数?

5 个答案:

答案 0 :(得分:10)

答案 1 :(得分:3)

这是计算树节点的递归实现。它被调用为根节点并返回“左子树中一个节点数加上右子树中节点数”,这是递归地完成的,直到到达叶节点。

答案 2 :(得分:1)

总计数包括当前/根节点加上左分支上的计数加上右分支上的计数。你的sentinel是NULL,这意味着你已经到达了你正在计算的任何分支的叶节点。然后你放松回来。递归:)

答案 3 :(得分:1)

首先,你自己试过吗?

基本上,它为每个非空节点添加1。它大致是这样的:1 + number_of_nodes_to_the_left + number_of_nodes_to_the_right。这扩展为:1+(1+number_of_nodes_to_the_left_in_left+number_of_nodes_to_the_right_in_left) + (1+number_of_nodes_to_the_left_in_right + number_of_nodes_to_the_right_in_right)。继续扩展,你会发现它对于树中的每个非空节点基本上都是1 + 1 + 1 +....

编辑:为了更好地说明这一点,请考虑以下树:

     Node0
       |
(left) |  (right)
Node1 _|_ Node2
            |
     (left) |  (right)
     Node3 _|_ Node4

执行int node_count = count(Node0)时,由于Node0不为NULL,因此转到return语句,即: return 1 + count(left) + count(right)。您需要了解一个基本的事情,即递归函数中的非常操作会在其后发生。换句话说,在操作count(right)完成之前,操作count(left)不会发生。现在看看你在那里的return语句,并根据上面的树来翻译它。它将是1+count(Node1)+count(Node2)。因此count(Node2)count(Node1)完成之前无法计算。因此,对于count(Node1),将使用Node1作为参数调用count函数(再次)。因此,现在让我们忘记半计算的表达式1+count(Node1)+count(Node2)(稍后我们会再回过头来看)。

现在对于count(Node1),Node1不是NULL,因此进入return语句。这将(再次)为1+count(left)+count(right)。但是等一下,Node1没有左右节点。因此,当参数为NULL时调用count(left)时,它返回0,count(right)也会发生同样的情况。因此count(Node1)的表达式变为1 + 0 + 0。没有为Node1调用计数函数,因此返回到它的原始调用者,这是 count(Node0) 的返回语句。

由于我们已经找到count(Node1),所以让我们在count(Node0)的return语句中替换它。现在变为1 + (1 + 0 + 0) + count(Node2)

现在我要更快一点。由于Node2有两个子节点,因此Node2的return语句将为1 + count(Node3) + count(Node4)。就像Node1一样,count(Node3)count(Node4)都会返回1 + 0 + 0,将count(Node2)的返回语句变为1 + (1 + 0 + 0) + (1 + 0 + 0)

现在已经完全计算了count(Node2),让返回count(Node2) 的原始调用者,即1 + (1 + 0 + 0) + count(Node2)。替换我们从count(Node2)获得的内容,我们得到1 + (1+0+0) + (1 + (1+0+0) + (1+0+0))。添加它,我们得到5的值。 此值将返回到调用count(Node0) 的任何函数,例如语句int node_count = count(Node0)node_count将具有值5

答案 4 :(得分:0)

考虑这些树:

没有节点的树(即NULL指针) - 返回0

具有一个节点的树,即根。这将打电话:

 i=1+count(t->left)+count(t->right);

左右NULL,因此将返回1 + 0 + 0

具有根和单个右叶的树

 i=1+count(t->left)+count(t->right);

将为根返回1,对于以左为根的树(按照上述规则)返回0,对于以右边为根的树(按照上述规则)返回1,即1 + 0 + 1

等等。