其他分享
首页 > 其他分享> > leetcode-94-二叉树的中序遍历

leetcode-94-二叉树的中序遍历

作者:互联网

 题目描述:

方法一:迭代

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res,stack = [],[]
        while True:
            while root:
                stack.append(root)
                root = root.left
            if not stack:
                return res
            node = stack.pop()
            res.append(node.val)
            root = node.right
        return res

方法二:递归

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def helper(root):
            if not root:
                return
            helper(root.left)
            res.append(root.val)
            helper(root.right)
        helper(root)
        return res

另;

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        f = self.inorderTraversal 
        return f(root.left) + [root.val] + f(root.right) if root else []

 

标签:return,helper,inorderTraversal,res,中序,stack,二叉树,root,leetcode
来源: https://www.cnblogs.com/oldby/p/11181674.html