下面這三個是我寫的.
static int node_count (const Tree tree)<br />{<br />int the_number_of_left_subtree = 0, the_number_of_right_subtree = 0, the_number_of_node = 0 ;</p><p>if (tree != NULL)<br />{<br />the_number_of_left_subtree = node_count (tree -> left) ;<br />the_number_of_right_subtree = node_count (tree -> right) ;<br />the_number_of_node = the_number_of_left_subtree + the_number_of_right_subtree + 1 ;<br />}</p><p>return the_number_of_node ;<br />}</p><p>static int leaf_count (const Tree tree)<br />{<br />int the_number_of_left_subtree = 0, the_number_of_right_subtree = 0, the_number_of_leaf = 0 ;</p><p>if (tree != NULL)<br />{<br />the_number_of_left_subtree = leaf_count (tree -> left) ;<br />the_number_of_right_subtree = leaf_count (tree -> right) ;<br />the_number_of_leaf = the_number_of_left_subtree + the_number_of_right_subtree ;<br />if (0 == the_number_of_left_subtree && 0 == the_number_of_right_subtree)<br />the_number_of_leaf++ ;<br />}</p><p>return the_number_of_leaf ;<br />}</p><p>static int full_count (const Tree tree)<br />{<br />int the_number_of_left_subtree = 0, the_number_of_right_subtree = 0, the_number_of_full_node = 0 ;</p><p>if (tree != NULL)<br />{<br />the_number_of_left_subtree = full_count (tree -> left) ;<br />the_number_of_right_subtree = full_count (tree -> right) ;<br />if (the_number_of_left_subtree != 0 && the_number_of_right_subtree != 0)<br />the_number_of_full_node += the_number_of_left_subtree + the_number_of_right_subtree + 1 ;<br />else if (tree -> left != NULL && tree -> right != NULL)<br />the_number_of_full_node++ ;<br />}</p><p>return the_number_of_full_node ;<br />}
下面這三個是答案給出的,看了讓人慚愧啊.
static int new_node_count (const Tree tree)<br />{<br />if (NULL == tree)<br />return 0;<br />return 1 + new_node_count (tree -> left) + new_node_count (tree -> right) ;<br />}</p><p>static int new_leaf_count (const Tree tree)<br />{<br />if (NULL == tree)<br />return 0;<br />else if (NULL == tree -> left && NULL == tree -> right)<br />return 1;<br />return new_leaf_count (tree -> left) + new_leaf_count (tree -> right) ;<br />}</p><p>static int new_full_count (const Tree tree)<br />{<br />if (NULL == tree)<br />return 0;<br />return (tree -> left != NULL && tree -> right != NULL) + new_full_count (tree -> left) + new_full_count (tree -> right) ;<br />}
雖然看懂了,但是叫我自己寫還是寫不出.總結些經驗的話,就是這種遞迴函式多利用return...