以二叉链表作为二叉树的存储结构, 编写以下算法: (2) 判别 两棵树是否相等。用c语言写出完整的代码与注释
时间: 2023-06-25 12:02:06 浏览: 122
以下是用 C 语言实现判断两棵树是否相等的算法,基于二叉链表存储结构:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义二叉树节点 */
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
/* 创建新节点 */
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
/* 判断两棵树是否相等 */
bool isSameTree(TreeNode* p, TreeNode* q) {
/* 两个指针都为空,则相等 */
if (p == NULL && q == NULL) {
return true;
}
/* 一个指针为空,另一个不为空,则不相等 */
if (p == NULL || q == NULL) {
return false;
}
/* 当前节点的值不同,则不相等 */
if (p->val != q->val) {
return false;
}
/* 递归判断左右子树是否相等 */
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
/* 测试 */
int main() {
/* 构造两棵树 */
TreeNode* p = createNode(1);
p->left = createNode(2);
p->right = createNode(3);
TreeNode* q = createNode(1);
q->left = createNode(2);
q->right = createNode(3);
/* 判断两棵树是否相等 */
if (isSameTree(p, q)) {
printf("两棵树相等\n");
} else {
printf("两棵树不相等\n");
}
return 0;
}
```
注释在代码中已经给出。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)