LeetCode 94 Binary Tree Inorder Traversal (Python)

Posted by 小明MaxMing on February 26, 2022

题目

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

解题思路

递归和非递归两种方法

代码

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

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅