力扣-数据结构-二叉树

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
相关推荐
老师我太想进步了2026几秒前
【数据结构-12】树与二叉树的结构、概念
数据结构
秋天的怀念_David1 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
泯泷3 小时前
别再“裸聊”大模型了!你家的 AI 为什么总胡说八道?根子在 RAG
人工智能·算法·架构
2601_967980114 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
zaizai10075 小时前
算法(左程云)2
数据结构
漂流瓶jz6 小时前
UVA-1615 高速公路 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·贪心算法·贪心·aoapc·算法竞赛入门经典·uva
夊6 小时前
数据结构第四课:栈与队列
数据结构
凌冰_16 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi16 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展