跳至主要內容
Binary Tree

本文主要研究了:

  • 二叉树的三种遍历方式:递归和迭代实现
  • 二叉树相关的例题解析

二叉树的前序遍历

递归法

# 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]:
        def preorder(node):
            if not node:
                return
            res.append(node.val)
            preorder(node.left)
            preorder(node.right)

        res = list()
        preorder(root)
        return res

Someone大约 15 分钟Algorithmbinary tree