判断对称二叉树

typedef struct node {
int x;
struct node* left;
struct node* right;
} BN;

不用关心输入,二叉树构造和删除过程已经在main函数中实现,需要你们实现函数

int isSymmetric(BN* root);

来判断一棵二叉树是否对称,对称返回1,非对称返回0.

node结构要按照上面的代码在symmetric.h中进行定义。

注意被测试二叉树不一定是满二叉树。如果树不存在(根节点指针为空)返回0。如果除根节点外没有任何的其他节点返回1。

#include<stdio.h>
#include<stdlib.h>
#define MAXD 50

typedef struct node {
    int x;
    struct node* left;
    struct node* right;
} BN;
int islink(BN *q, BN *p) {
    if (q == NULL && p == NULL) {
        return 1;
    }
    if (p != NULL && q != NULL && q->x == p->x) {
        return islink(q->left, p->right) && islink(q->right, p->left);
    } else {
        return 0;
    }
}

int isSymmetric(BN* pRoot) {
    if (pRoot == NULL) {
        return 0;
    }
    return islink(pRoot->left, pRoot->right);
}

//用队列建二叉树
void buildTree(BN** root) {
    int temp;
    BN** que[MAXD];
    int head = 0;
    int tail = 1;
    que[0] = root;
    scanf("%d", &temp);
    while (temp != -1) {
        *que[head] = malloc(sizeof(struct node));
        (*que[head])->x = temp;
        que[tail] = &((*que[head])->left);
        tail = (tail + 1) % MAXD;
        que[tail] = &((*que[head])->right);
        tail = (tail + 1) % MAXD;
        head = (head + 1) % MAXD;
        scanf("%d", &temp);
    }
    while (head != tail) {
        *que[head] = NULL;
        head = (head + 1) % MAXD;
    }
}
//后序遍历释放内存
void freeTree(BN* root) {
    if (root != NULL) {
        freeTree(root->left);
        freeTree(root->right);
        free(root);
    }
}
int main() {
    BN* root = NULL;
    buildTree(&root);
    printf("%d\n", isSymmetric(root));
    freeTree(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值