检查完整二叉树错误

时间:2016-10-23 10:50:23

标签: c++

我有一个函数来检查树是否是完整的树:

int checkfull(plant* root){
    if (root == NULL)
        return 1;
    else if (root->pLeft == NULL && root->pRight == NULL)
        return 1;
    else if ((root->pLeft == NULL && root->pRight != NULL) || (root->pLeft != NULL && root->pRight == NULL))
        return 0;
    else
        return (checkfull(root->pLeft) && checkfull(root->pRight));
}

但问题是树是这样的:

enter image description here

回报是1,我不知道为什么?

1 个答案:

答案 0 :(得分:0)

你必须使用你的调试器,算法正在执行除外的工作并返回0。 这是我的可疑树的测试代码(我添加了一个sID参数来将节点标识为dsiplayed):

#include <stdio.h>

typedef struct splant {
    struct splant *pLeft;
    struct splant *pRight;
    char *sId;
} plant;

int checkfull(plant* root){
    if (root == NULL)
        return 1;
    else if (root->pLeft == NULL && root->pRight == NULL)
        return 1;
    else if ((root->pLeft == NULL && root->pRight != NULL) || (root->pLeft != NULL && root->pRight == NULL))
        return 0;
    else
        return (checkfull(root->pLeft) && checkfull(root->pRight));
}

int main()
{
    plant p0103[] = { NULL, NULL, "0103" };
    plant p0141[] = { NULL, NULL, "0141" };
    p0141->pLeft = p0103;
    plant p0900[] = { NULL, NULL, "0900" };
    plant p0863[] = { NULL, NULL, "0863" };
    p0863->pRight = p0900;
    plant p0523[] = { NULL, NULL, "0523" };
    p0523->pLeft = p0141;
    p0523->pRight = p0863;

    int iRes = checkfull(p0523);

    return (0);
}