計算二叉樹中節點個數,分葉節點個數,滿節點個數的函數

來源:互聯網
上載者:User

下面這三個是我寫的.

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...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.