题目:
题解:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSymmetric(struct TreeNode* root) {
if (root == NULL) return true;//如果根为空直接返回true
struct TreeNode* p = root->left;
struct TreeNode* q = root->right;//一个指向左子树,一个指向右子树
struct TreeNode** stk1 = malloc(550 * sizeof(struct TreeNode));
struct TreeNode** stk2 = malloc(550 * sizeof(struct TreeNode));//创建栈
int top1 = 0, top2 = 0;//创建栈顶指针
while ((p != NULL || q != NULL) || (top1 != 0 && top2 != 0)) {//栈不空或结点不全为空时循环
if (p != NULL && q != NULL) {//两个结点都不空时
if (p->val != q->val) return false;//结点值不同直接false
stk1[top1++] = p;
stk2[top2++] = q;//入栈
p = p->left;
q = q->right;//指针镜像移动
}
else if (p == NULL && q == NULL) {//两个结点都为空时
p = stk1[--top1];
q = stk2[--top2];//接收栈顶结点
p = p->right;
q = q->left;//指针镜像移动
}
else return false;//如果一个结点为空而另一个不为空时,直接false
}
return true;//经过以上处理后,此时栈已经空了,并且所有结点已经镜像遍历并比较过了,直接返回true
}