返回

LeetCode-144:探究二叉树的前序遍历(Day33)

后端

前序遍历
前序遍历是一种深度优先搜索算法,它以深度优先的方式遍历二叉树。在进行前序遍历时,我们首先访问根结点,然后访问其左子结点,最后访问其右子结点。前序遍历的顺序是:根结点、左子结点、右子结点。

递归实现

前序遍历可以使用递归算法来实现。递归算法是一种解决问题的策略,它将问题分解成更小的子问题,然后递归地解决这些子问题,直到子问题足够小,可以直接解决。

def preorder_traversal_recursive(root):
  """
  Recursive implementation of preorder traversal.

  Args:
    root: The root node of the binary tree.

  Returns:
    A list of the values of the nodes in the binary tree in preorder.
  """

  if root is None:
    return []

  return [root.val] + preorder_traversal_recursive(root.left) + preorder_traversal_recursive(root.right)

非递归实现

前序遍历也可以使用非递归算法来实现。非递归算法是一种解决问题的策略,它不使用递归调用,而是使用迭代来解决问题。

def preorder_traversal_iterative(root):
  """
  Iterative implementation of preorder traversal.

  Args:
    root: The root node of the binary tree.

  Returns:
    A list of the values of the nodes in the binary tree in preorder.
  """

  stack = [root]
  result = []

  while stack:
    node = stack.pop()

    if node is not None:
      result.append(node.val)
      stack.append(node.right)
      stack.append(node.left)

  return result

时间复杂度

前序遍历的时间复杂度为O(n),其中n是二叉树的结点数。这是因为前序遍历需要访问二叉树中的每个结点,因此时间复杂度为O(n)。

空间复杂度

前序遍历的空间复杂度为O(n),其中n是二叉树的结点数。这是因为前序遍历需要使用栈来存储结点,因此空间复杂度为O(n)。

二叉搜索树中的应用

前序遍历在二叉搜索树中有很多应用。例如,我们可以使用前序遍历来验证二叉搜索树的顺序性。我们也可以使用前序遍历来找到二叉搜索树中的最小值和最大值。

总结

前序遍历是一种深度优先搜索算法,它以深度优先的方式遍历二叉树。前序遍历的时间复杂度为O(n),空间复杂度为O(n)。前序遍历在二叉搜索树中有很多应用。