LeetCode(力扣)144. 二叉树的前序遍历Python

LeetCode144. 二叉树的前序遍历

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/binary-tree-preorder-traversal/
LeetCode(力扣)144. 二叉树的前序遍历Python_第1张图片

代码

递归遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        left = self.preorderTraversal(root.left)
        right = self.preorderTraversal(root.right)

        return [root.val] + left + right

迭代遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        stack = [root]
        result = []
        while stack:
            node = stack.pop()
            result.append(node.val)

            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return resultnode.left)
        return result

你可能感兴趣的:(leetcode,python,算法)