LeetCode 144 Binary Tree Preorder Traversal (Python)

Posted by 小明MaxMing on February 26, 2022

题目

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

解题思路

递归和非递归两种方法

代码

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

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

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