Skip to content

Latest commit

 

History

History
27 lines (26 loc) · 920 Bytes

32. 二叉树的中序遍历.md

File metadata and controls

27 lines (26 loc) · 920 Bytes

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

# 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]:
        #思路:栈,中序遍历:左,中,右,那么入栈顺序必须调整为倒序,也就是右,中,左
        UNUSED, USED = 0, 1
        stack=[(UNUSED, root)]
        res = []
        while stack:
            state, node = stack.pop()
            if not node:
                continue
            if state == 0:
                stack.append((UNUSED, node.right))
                stack.append((USED, node))
                stack.append((UNUSED, node.left))
            else:
                res.append(node.val)
        return res