94. 二叉树的中序遍历



方法一:迭代

class Solution(object):
    # 迭代
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        mid_stack = []
        ans = []
        cur = root
        while cur or mid_stack:
            while cur:
                mid_stack.append(cur)
                cur = cur.left
            temp = mid_stack.pop()
            ans.append(temp.val)
            cur = temp.right
        return ans

方法二:递归

class Solution(object):
    # 递归
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
posted @ 2020-08-30 16:14  人间烟火地三鲜  阅读(109)  评论(0编辑  收藏  举报