c++ - 在二叉树中,找出有多少祖父只有两个或三个孙子

标签 c++ c binary-tree

                                   8
                                /      \
                              4         12
                             / \         / \
                           3    6       2   1
                          / \   / \    /   / \
                         7  10 13 15  5   9  11
                                             /
                                            14 

我需要找到一棵树的祖父,在这个例子中我只有一个祖父,12 号(我需要他只有两个或三个孙子)。

这是我到目前为止尝试过的:

int T(struct node * tree){
    int t = 0;
    if (tree == NULL)
        return 0;
    if (tree->left && tree->right)
    {    //In this case i check if we NOT have all the four grandchildrens.
        if (!((tree->left->left) && (tree->left->right) && (tree->right->left) && (tree->right->right)))
        {
            t =  1 + T(tree->left) + T(tree->right);
            T(tree->left);
            T(tree->right);

        }
        else
       {
            T(tree->left);
            T(tree->right);
        }

    }

    return t;

}

不幸的是,它不起作用...有人可以帮我解决这个问题吗?

最佳答案

一种有效的方法是递归地返回一对结果。在 C++ 中有更优雅的方法来返回一对,但我将使用旧的笨拙的 C 方法通过指针输入返回一个输出:

int T2(struct node * tree, int* child_count)
{
    int t = 0;  // Count the things we are supposed to count
    int g = 0;  // Count grandchildren of the current node
    if (tree == NULL)
        return 0;
    if ( tree->left )
    {
       ++ *child_count;
       t += T2( tree->left, &g );
    }
    if ( tree->right )
    {
       ++ *child_count;
       t += T2( tree->right, &g );
    }
    if ( g==2 || g==3 )
       ++t;
    return t; 
}

int T(struct node * tree) {int dummy; return T2(tree, &dummy); }

这个函数同时做了两件事。简单的工作是它通过递增 *child_count 来帮助计算其 parent 的孙子,它还通过在 t 中累加来递归地完成主要工作。


下面的方式可能更容易理解,但不够优雅:

int T(struct node * tree)
{
    struct node *c;
    int t = 0;  // Count the things we are supposed to count
    int g = 0;  // Count grandchildren of the current node
    if (tree == NULL)
        return 0;
    if ( (c=tree->left) != NULL )
    {
       g += (c->left != NULL) + (c->right != NULL);
       t += T( c );
    }
    if ( (c=tree->right) != NULL )
    {
       g += (c->left != NULL) + (c->right != NULL);
       t += T( c );
    }
    if ( g==2 || g==3 )
       ++t;
    return t; 
}

关于c++ - 在二叉树中,找出有多少祖父只有两个或三个孙子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34483586/

相关文章:

C++ 将参数传递给 lambda 函数

c - 为什么需要转换从函数返回的结构?

c - 在这个用 C 语言编写的生命游戏程序中,我无法在数组周围建立边界

c++ - 从二叉树中删除并查找节点

c - c中存储任何数据类型的二叉树

Java二叉树add方法覆盖写入root

c++ - 无法使用()创建原子

c++ - 将元组成员包装在其他模板化类型中

c++ - 我们可以将 printf() 打印的值存储到 unsigned long 变量中吗?

c - 从C语言的文本文件中读取数据?