力扣-数据结构-二叉树

94. 二叉树的中序遍历

给定一个二叉树的根节点 root ,返回 它的 中序 遍历

示例 1:

复制代码
输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:

复制代码
输入:root = []
输出:[]

示例 3:

复制代码
输入:root = [1]
输出:[1]

方法一:递归实现(最简单)

python 复制代码
# 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 inorderTraversal(self, root: TreeNode) -> list[int]:
        result = []

        def dfs(node):
            if not node:
                return
            dfs(node.left)
            result.append(node.val)
            dfs(node.right)

        dfs(root)
        return result

方法二:迭代实现(使用栈)

python 复制代码
class Solution:
    def inorderTraversal(self, root: TreeNode) -> list[int]:
        result = []
        stack = []
        current = root

        while current or stack:
            while current:
                stack.append(current)
                current = current.left  # 一直往左走
            current = stack.pop()
            result.append(current.val)
            current = current.right  # 然后往右走

        return result
相关推荐
xiaoye-duck6 分钟前
《算法题讲解指南:优选算法-双指针》--05有效三角形的个数,06查找总价值为目标值的两个商品
c++·算法
ArturiaZ9 分钟前
【day31】
开发语言·c++·算法
xiaoye-duck13 分钟前
《算法题讲解指南:优选算法-双指针》--07三数之和,08四数之和
c++·算法
琢磨先生David17 分钟前
Java每日一题
数据结构·算法·leetcode
im_AMBER21 分钟前
Leetcode 125 验证回文串 | 判断子序列
数据结构·学习·算法·leetcode
List<String> error_P22 分钟前
蓝桥杯高频考点练习:模拟问题“球队比分类”
数据结构·python·算法·模拟·球队比分
daxi15027 分钟前
C语言从入门到进阶——第8讲:VS实用调试技巧
c语言·开发语言·c++·算法·蓝桥杯
m0_5312371731 分钟前
C语言-数组
c语言·开发语言·算法
啊阿狸不会拉杆32 分钟前
《计算机视觉:模型、学习和推理》第 4 章-拟合概率模型
人工智能·python·学习·算法·机器学习·计算机视觉·拟合概率模型
ADDDDDD_Trouvaille35 分钟前
2026.2.20——OJ92-94题
c++·算法