leetcode101—对称二叉树c语言
时间: 2025-02-28 22:54:42 浏览: 62
### LeetCode 101 对称二叉树 C语言实现
#### 递归方法
为了判断一棵二叉树是否为对称结构,可以采用递归的方法来比较两棵子树。具体来说,要验证整棵树是否对称,则需确认其左子树与右子树互为镜像。
对于任意节点而言,只有当该节点的左右孩子均为空或两者皆不为空且值相等时才满足条件;接着再分别对比当前节点左侧孩子的左子树同右侧孩子的右子树以及左侧孩子的右子树同右侧孩子的左子树之间的关系即可[^4]。
下面是具体的C语言代码:
```c
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isMirror(struct TreeNode* t1, struct TreeNode* t2){
if (t1 == NULL && t2 == NULL) return true; // 如果两个都是NULL则返回true
if (t1 == NULL || t2 == NULL) return false; // 只有一个是NULL则不对称
// 值相同的情况下继续检查各自的左右分支是否也构成镜子映射的关系
return (t1->val == t2->val) &&
isMirror(t1->right, t2->left) &&
isMirror(t1->left, t2->right);
}
bool isSymmetric(struct TreeNode* root){
return isMirror(root, root); // 调用辅助函数isMirror来进行实际运算
}
```
此段程序通过定义了一个名为`isMirror()`的帮助函数用于检测给定的一对节点`t1`和`t2`所代表的子树之间是否存在镜面对应关系,并最终利用它完成整个过程中的核心逻辑处理工作[^5]。
#### 迭代方法
除了上述提到的基于栈帧调用来解决问题的方式外,还可以借助队列这种数据结构以迭代的形式达成同样的目的——即每次取出一对待考察的对象并将其对应的四个方向上的邻接点依次入队等待后续进一步检验直至遍历完毕为止[^1]。
以下是使用广度优先搜索(BFS)策略下的另一种可能解决方案:
```c
#include <stdbool.h>
#include <stdlib.h>
typedef struct QueueNode{
struct TreeNode *data;
struct QueueNode *next;
}QueueNode;
// 初始化队列操作...
void initQueue(QueueNode **front, QueueNode **rear);
// 入队操作...
void enqueue(QueueNode **front, QueueNode **rear, struct TreeNode *item);
// 出队操作...
struct TreeNode* dequeue(QueueNode **front, QueueNode **rear);
bool check(struct TreeNode *u, struct TreeNode *v){
QueueNode *q_front = NULL,* q_rear = NULL;
initQueue(&q_front,&q_rear);
enqueue(&q_front,&q_rear,u);
enqueue(&q_front,&q_rear,v);
while(q_front != NULL){
u = dequeue(&q_front,&q_rear);
v = dequeue(&q_front,&q_rear);
if(!u && !v) continue;
if((!u||!v)||(u->val!=v->val)) return false;
enqueue(&q_front,&q_rear,u->left);
enqueue(&q_front,&q_rear,v->right);
enqueue(&q_front,&q_rear,u->right);
enqueue(&q_front,&q_rear,v->left);
}
return true;
}
bool isSymmetric(struct TreeNode* root){
return check(root,root);
}
```
这段代码实现了非递归版的算法流程,在这里引入了额外的数据容器(如链表形式表示的队列),以便于按照层次顺序逐层访问各个顶点及其关联边的信息从而达到预期效果。
阅读全文
相关推荐


















