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

94. 二叉树的中序遍历

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

img

示例 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%的用户

原文地址:https://www.cnblogs.com/hereisdavid/p/15340960.html