用C语言写一段判断二叉树左右子树是否同构的代码
时间: 2024-05-02 15:20:41 浏览: 164
好的,以下是用C语言写的判断二叉树左右子树是否同构的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char val;
struct node* left;
struct node* right;
} Node;
int isIsomorphic(Node* root1, Node* root2) {
// 如果两个节点都为空,则认为它们同构
if (!root1 && !root2) {
return 1;
}
// 如果只有一个节点为空,则认为它们不同构
if (!root1 || !root2) {
return 0;
}
// 如果节点的值不同,则认为它们不同构
if (root1->val != root2->val) {
return 0;
}
// 分别比较左右子树
return (isIsomorphic(root1->left, root2->left) && isIsomorphic(root1->right, root2->right)) ||
(isIsomorphic(root1->left, root2->right) && isIsomorphic(root1->right, root2->left));
}
int main() {
// 构造两棵二叉树
Node* root1 = (Node*)malloc(sizeof(Node));
Node* root2 = (Node*)malloc(sizeof(Node));
root1->val = 'a';
root1->left = (Node*)malloc(sizeof(Node));
root1->left->val = 'b';
root1->left->left = NULL;
root1->left->right = (Node*)malloc(sizeof(Node));
root1->left->right->val = 'c';
root1->left->right->left = NULL;
root1->left->right->right = NULL;
root1->right = (Node*)malloc(sizeof(Node));
root1->right->val = 'd';
root1->right->left = (Node*)malloc(sizeof(Node));
root1->right->left->val = 'e';
root1->right->left->left = NULL;
root1->right->left->right = NULL;
root1->right->right = (Node*)malloc(sizeof(Node));
root1->right->right->val = 'f';
root1->right->right->left = NULL;
root1->right->right->right = NULL;
root2->val = 'a';
root2->left = (Node*)malloc(sizeof(Node));
root2->left->val = 'd';
root2->left->left = (Node*)malloc(sizeof(Node));
root2->left->left->val = 'f';
root2->left->left->left = NULL;
root2->left->left->right = NULL;
root2->left->right = (Node*)malloc(sizeof(Node));
root2->left->right->val = 'e';
root2->left->right->left = NULL;
root2->left->right->right = NULL;
root2->right = (Node*)malloc(sizeof(Node));
root2->right->val = 'b';
root2->right->left = NULL;
root2->right->right = (Node*)malloc(sizeof(Node));
root2->right->right->val = 'c';
root2->right->right->left = NULL;
root2->right->right->right = NULL;
// 判断两棵二叉树是否同构
if (isIsomorphic(root1, root2)) {
printf("两个二叉树同构\n");
} else {
printf("两个二叉树不同构\n");
}
// 释放内存
free(root1->left->right);
free(root1->left);
free(root1->right->left);
free(root1->right->right);
free(root1->right);
free(root1);
free(root2->left->left);
free(root2->left->right);
free(root2->left);
free(root2->right->right);
free(root2->right);
free(root2);
return 0;
}
```
阅读全文