94. 二叉树的中序遍历 (二叉树遍历整理)

二叉树遍历整理:

94. 二叉树的中序遍历 - 力扣(LeetCode)https://leetcode.cn/problems/binary-tree-inorder-traversal/solutions/324347/python3-er-cha-shu-suo-you-bian-li-mo-ban-ji-zhi-s/?envType=study-plan-v2&envId=top-100-liked

最易理解的代码:

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: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        
        return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)

栈:

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: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        
        res = []
        stack = []
        cur = root
        while stack or cur:
            while cur:
                stack.append(cur)
                cur=cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur=cur.right
        
        return res
相关推荐
信奥卷王5 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵5 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG7 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
码完就睡7 小时前
数据结构——红黑树
数据结构
码爸7 小时前
数据结构详细介绍
数据结构
Navigator_Z7 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛8 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记8 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序8 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm