对称二叉树

GitHub跳转原题关系图返回列表

定义 mirror(a,b):值相等且 a.left 对 b.right、a.right 对 b.left。

OJ: leetcodecn

题目 ID: symmetric-tree

难度:入门

标签:二叉树递归BFScpppython

日期: 2026-07-28 22:05

题意

判断二叉树是否轴对称(镜像对称)。

思路

递归定义:两棵树互为镜像当且仅当根值相等且 a.left 与 b.right 镜像、a.right 与 b.left 镜像。根节点的左右子树就是一对待检查的镜像。

代码

cpp
/**
 * Author by Rainboy
 */
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root)
            return true;
        function<bool(TreeNode *, TreeNode *)> dfs = [&](TreeNode *a, TreeNode *b) {
            if (!a && !b)
                return true;
            if (!a || !b)
                return false;
            return a->val == b->val && dfs(a->left, b->right) && dfs(a->right, b->left);
        };
        return dfs(root->left, root->right);
    }
};

TreeNode *build(istream &in, int n) {
    if (!n)
        return nullptr;
    vector<TreeNode *> nodes(n);
    for (int i = 0, v; i < n; i++) {
        in >> v;
        if (v != -1)
            nodes[i] = new TreeNode(v);
    }
    queue<TreeNode *> q;
    TreeNode *root = nodes[0];
    if (root)
        q.push(root);
    int idx = 1;
    while (!q.empty() && idx < n) {
        auto cur = q.front();
        q.pop();
        if (idx < n) {
            cur->left = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
        if (idx < n) {
            cur->right = nodes[idx];
            if (nodes[idx])
                q.push(nodes[idx]);
            idx++;
        }
    }
    return root;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    auto root = build(cin, n);
    cout << Solution().isSymmetric(root) << '\n';
    return 0;
}
python
#!/usr/bin/env python3
from collections import deque
from typing import Optional


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def dfs(a, b):
            if not a and not b:
                return True
            if not a or not b:
                return False
            return a.val == b.val and dfs(a.left, b.right) and dfs(a.right, b.left)

        return dfs(root.left, root.right) if root else True


def build(arr):
    if not arr:
        return None
    nodes = [TreeNode(v) if v != -1 else None for v in arr]
    q = deque()
    root = nodes[0]
    if root:
        q.append(root)
    idx = 1
    while q and idx < len(arr):
        cur = q.popleft()
        if idx < len(arr):
            cur.left = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
        if idx < len(arr):
            cur.right = nodes[idx]
            if nodes[idx]:
                q.append(nodes[idx])
            idx += 1
    return root


def main() -> None:
    n = int(input())
    a = list(map(int, input().split()))
    root = build(a)
    print(Solution().isSymmetric(root))


if __name__ == "__main__":
    main()

复杂度

  • 时间复杂度:O(n)。
  • 空间复杂度:O(height)。

总结

对称树的递归定义本身就是镜像检查的算法。