翻转二叉树

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

后序/前序递归交换左右子树。

OJ: leetcodecn

题目 ID: invert-binary-tree

难度:入门

标签:二叉树递归cpppython

日期: 2026-07-28 22:05

题意

翻转二叉树(镜像对称)。

思路

递归:交换当前节点的左右子树,然后递归翻转左右子树。前序和后序都可以,中序需要特殊处理。

代码

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:
    TreeNode *invertTree(TreeNode *root) {
        if (!root)
            return nullptr;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

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);
    }
    for (int i = 0; i < n; i++) {
        if (!nodes[i])
            continue;
        int l = 2 * i + 1, r = 2 * i + 2;
        if (l < n)
            nodes[i]->left = nodes[l];
        if (r < n)
            nodes[i]->right = nodes[r];
    }
    return nodes[0];
}

void print(TreeNode *r) {
    if (!r)
        return;
    queue<TreeNode *> q;
    q.push(r);
    while (!q.empty()) {
        auto p = q.front();
        q.pop();
        if (!p) {
            cout << "-1 ";
            continue;
        }
        cout << p->val << ' ';
        q.push(p->left);
        q.push(p->right);
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    auto root = build(cin, n);
    root = Solution().invertTree(root);
    print(root);
    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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root


def build(arr):
    if not arr:
        return None
    nodes = [TreeNode(v) if v != -1 else None for v in arr]
    for i in range(len(nodes)):
        if nodes[i] is None:
            continue
        l, r = 2 * i + 1, 2 * i + 2
        if l < len(nodes):
            nodes[i].left = nodes[l]
        if r < len(nodes):
            nodes[i].right = nodes[r]
    return nodes[0]


def print_tree(r):
    if not r:
        return
    q = deque([r])
    while q:
        p = q.popleft()
        if not p:
            print("-1", end=" ")
            continue
        print(p.val, end=" ")
        q.append(p.left)
        q.append(p.right)


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


if __name__ == "__main__":
    main()

复杂度

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

总结

翻转二叉树是递归思维的经典入门练习——先交换、再递归处理子树。