Leetcode python 94. 二叉树的中序遍历

发布时间:2022-07-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Leetcode python 94. 二叉树的中序遍历脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_777_0@94. 二叉树的中序遍历

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

Leetcode python 94. 二叉树的中序遍历

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

示例 2: 输入:root = [] 输出:[]

示例 3: 输入:root = [1] 输出:[1]

示例 4: 输入:root = [1,2] 输出:[2,1]

示例 5: 输入:root = [1,null,2] 输出:[1,2]

颜色标记法

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        WHITE, GRAY = 0, 1
        res = []
        stack = [(WHITE, root)]
        while stack:
            color, node = stack.pop()
            if node is None: continue
            if color == WHITE:
                stack.apPEnd((WHITE, node.right))
                stack.append((GRAY, node))
                stack.append((WHITE, node.left))
            else:
                res.append(node.val)
        return res

执行用时:28 ms, 在所有 Python3 提交中击败了88.88%的用户 内存消耗:14.8 MB, 在所有 Python3 提交中击败了93.26%的用户

脚本宝典总结

以上是脚本宝典为你收集整理的Leetcode python 94. 二叉树的中序遍历全部内容,希望文章能够帮你解决Leetcode python 94. 二叉树的中序遍历所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。