美文网首页
94. Binary Tree Inorder Traversa

94. Binary Tree Inorder Traversa

作者: GoDeep | 来源:发表于2018-04-27 16:16 被阅读0次

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1

2
/
3

Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?

还是维护一个p指针吧,不要直接用stack里面的值

class Solution:
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root: return []
        res = []
        st = []
        p = root
        while p or st:
            while p:
                st.append(p)
                p = p.left
            t = st.pop()
            res.append(t.val)
            p = t.right
        return res

相关文章

网友评论

      本文标题:94. Binary Tree Inorder Traversa

      本文链接:https://www.haomeiwen.com/subject/wxfilftx.html