# 28.对称的二叉树

## 题目

请实现一个函数，用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样，那么它是对称的。

例如，二叉树 \[1,2,2,3,4,4,3] 是对称的。

```
     1
    / \
   2   2
  / \ / \
 3  4 4  3
```

但是下面这个 \[1,2,2,null,3,null,3] 则不是镜像对称的:

```
     1
    / \
   2   2
    \   \
    3    3
```

示例 1：

输入：root = \[1,2,2,3,4,4,3] 输出：true 示例 2：

输入：root = \[1,2,2,null,3,null,3] 输出：false

限制：

0 <= 节点个数 <= 1000

注意：本题与主站 101 题相同：<https://leetcode-cn.com/problems/symmetric-tree/>

来源：力扣（LeetCode） 链接：<https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof> 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

## 题解

递归

```swift
func isSymmetric(_ root: TreeNode?) -> Bool {
    func compare(tree1: TreeNode?, tree2: TreeNode?) -> Bool {
        if tree1 == nil && tree2 == nil {
            return true
        }
        else if tree1 == nil || tree2 == nil {
            return false
        }
        else if tree1?.val != tree2?.val {
            return false
        }
        return compare(tree1: tree1?.left, tree2: tree2?.right) && compare(tree1: tree1?.right, tree2: tree2?.left)
    }

    return compare(tree1: root?.left, tree2: root?.right)
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/28.-dui-cheng-de-er-cha-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
