94. 二叉树的中序遍历

  1. 题目链接

  2. 解题思路:中序遍历:左中右,用一个栈,同时用空来标识「中」,所以入栈顺序就是右->中->None->左

  3. 代码

    class Solution:
        def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
            # 使用栈
            # 中序的顺序,左中右   压栈就是右中左   为了标识「中」,就压右中null左,那么遇到null,就知道下面是中了
            ans = []
            if root is None:
                return ans
            stack = []
            stack.append(root)
            while stack:
                cur = stack.pop()
                if cur:
                    # 右中null左
                    if cur.right:
                        stack.append(cur.right)
                    stack.append(cur)
                    stack.append(None)
                    if cur.left:
                        stack.append(cur.left)
                else:
                    cur = stack.pop()
                    ans.append(cur.val)
            return ans
    
posted @ 2024-12-25 15:09  ouyangxx  阅读(18)  评论(0)    收藏  举报