LeetCode 题解工作台

翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。 示例 1: 输入: root = [4,2,7,1,3,6,9] 输出: [4,7,2,9,6,3,1] 示例 2: 输入: root = [2,1,3] 输出: [2,3,1] 示例 3: 输入: root = [] 输出: […

category

4

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·树·traversal

bolt

答案摘要

我们首先判断 是否为空,若为空则直接返回 。然后递归地对树的左右子树进行翻转,将翻转后的右子树作为新的左子树,将翻转后的左子树作为新的右子树,返回 。 时间复杂度 ,空间复杂度 。其中 是二叉树的节点个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

 

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

输入:root = []
输出:[]

 

提示:

  • 树中节点数目范围在 [0, 100]
  • -100 <= Node.val <= 100
lightbulb

解题思路

方法一:递归

我们首先判断 root\textit{root} 是否为空,若为空则直接返回 null\text{null}。然后递归地对树的左右子树进行翻转,将翻转后的右子树作为新的左子树,将翻转后的左子树作为新的右子树,返回 root\textit{root}

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是二叉树的节点个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None
        l, r = self.invertTree(root.left), self.invertTree(root.right)
        root.left, root.right = r, l
        return root
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They want to see that you reduce the problem to one local operation repeated over the whole tree: swap left and right at every node.

  • question_mark

    They may ask for both recursive DFS and iterative BFS to check whether you understand traversal choice versus inversion logic.

  • question_mark

    They are watching for whether you handle the empty tree immediately and return the original root reference after mutation.

warning

常见陷阱

外企场景
  • error

    Recursing before preserving or swapping child pointers correctly, which can make the traversal harder to reason about.

  • error

    Overcomplicating the solution with extra arrays or rebuilding nodes when the problem only needs pointer swaps in place.

  • error

    Forgetting that an empty tree is valid input and should return an empty result without further work.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Invert the tree iteratively with a stack instead of recursion, using the same swap-at-each-node rule.

  • arrow_right_alt

    Return a new inverted tree without mutating the original, which changes the trade-off from pointer swapping to node reconstruction.

  • arrow_right_alt

    Invert only nodes below a certain depth, where traversal still matters but the swap condition becomes selective.

help

常见问题

外企场景

翻转二叉树题解:二分·树·traversal | LeetCode #226 简单