题目:
题解:
/*** 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;//如果根为空直接返回truestruct 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;//结点值不同直接falsestk1[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}