计算二叉树中节点个数,叶节点个数,满节点个数的函数

下面这三个是我写的.

static int node_count (const Tree tree) { int the_number_of_left_subtree = 0, the_number_of_right_subtree = 0, the_number_of_node = 0 ; if (tree != NULL) { the_number_of_left_subtree = node_count (tree -> left) ; the_number_of_right_subtree = node_count (tree -> right) ; the_number_of_node = the_number_of_left_subtree + the_number_of_right_subtree + 1 ; } return the_number_of_node ; } static int leaf_count (const Tree tree) { int the_number_of_left_subtree = 0, the_number_of_right_subtree = 0, the_number_of_leaf = 0 ; if (tree != NULL) { the_number_of_left_subtree = leaf_count (tree -> left) ; the_number_of_right_subtree = leaf_count (tree -> right) ; the_number_of_leaf = the_number_of_left_subtree + the_number_of_right_subtree ; if (0 == the_number_of_left_subtree && 0 == the_number_of_right_subtree) the_number_of_leaf++ ; } return the_number_of_leaf ; } static int full_count (const Tree tree) { int the_number_of_left_subtree = 0, the_number_of_right_subtree = 0, the_number_of_full_node = 0 ; if (tree != NULL) { the_number_of_left_subtree = full_count (tree -> left) ; the_number_of_right_subtree = full_count (tree -> right) ; if (the_number_of_left_subtree != 0 && the_number_of_right_subtree != 0) the_number_of_full_node += the_number_of_left_subtree + the_number_of_right_subtree + 1 ; else if (tree -> left != NULL && tree -> right != NULL) the_number_of_full_node++ ; } return the_number_of_full_node ; }

下面这三个是答案给出的,看了让人惭愧啊.

static int new_node_count (const Tree tree) { if (NULL == tree) return 0; return 1 + new_node_count (tree -> left) + new_node_count (tree -> right) ; } static int new_leaf_count (const Tree tree) { if (NULL == tree) return 0; else if (NULL == tree -> left && NULL == tree -> right) return 1; return new_leaf_count (tree -> left) + new_leaf_count (tree -> right) ; } static int new_full_count (const Tree tree) { if (NULL == tree) return 0; return (tree -> left != NULL && tree -> right != NULL) + new_full_count (tree -> left) + new_full_count (tree -> right) ; }

虽然看懂了,但是叫我自己写还是写不出.总结些经验的话,就是这种递归函数多利用return…

    原文作者:满二叉树
    原文地址: https://blog.csdn.net/Golden_Shadow/article/details/5921195
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞