返回

用Python征服LeetCode 112、222,成为算法大师!

前端

LeetCode 112和LeetCode 222都是计算机算法竞赛中的经典题题,它们能帮助您掌握算法原理并提高您的算法能力。本指南将使用Python语言,通过详细的步骤和示例代码,帮助您彻底理解并轻松解决这两道题题。

LeetCode 112:路径总和

问题

给定一个二叉树和一个目标和,判断是否存在从根节点到叶节点的路径,该路径上的节点值之和恰好是目标和。

算法思路:

  1. 从根节点开始,遍历二叉树。
  2. 在每个节点,将目标和减去该节点的值,并检查是否为0。
  3. 如果是0,则该路径是有效的,返回True。
  4. 否则,继续遍历该节点的左右子树,直到找到一条有效的路径或到达叶节点。

Python代码:

def has_path_sum(root, target_sum):
  """
  判断二叉树中是否存在从根节点到叶节点的路径,该路径上的节点值之和恰好是目标和。

  Args:
    root: 二叉树的根节点。
    target_sum: 目标和。

  Returns:
    True如果存在这样的路径,否则返回False。
  """

  if not root:
    return False

  if not root.left and not root.right:
    return root.val == target_sum

  return has_path_sum(root.left, target_sum - root.val) or has_path_sum(root.right, target_sum - root.val)

LeetCode 222:完全二叉树的节点个数

问题:

给定一个完全二叉树,求其节点个数。

算法思路:

  1. 使用递归的方法,将完全二叉树分为两半,分别计算左右子树的节点个数。
  2. 将左右子树的节点个数相加,得到完全二叉树的节点个数。

Python代码:

def count_nodes(root):
  """
  计算完全二叉树的节点个数。

  Args:
    root: 完全二叉树的根节点。

  Returns:
    完全二叉树的节点个数。
  """

  if not root:
    return 0

  left_height = get_height(root.left)
  right_height = get_height(root.right)

  if left_height == right_height:
    return 2 ** left_height - 1

  else:
    return 1 + count_nodes(root.left) + count_nodes(root.right)


def get_height(root):
  """
  计算二叉树的高度。

  Args:
    root: 二叉树的根节点。

  Returns:
    二叉树的高度。
  """

  if not root:
    return 0

  return 1 + max(get_height(root.left), get_height(root.right))

结语

通过LeetCode 112和LeetCode 222这两道题题,您已经掌握了基本的算法原理和实现方法。LeetCode还有更多精彩的题题等着您去探索,继续练习,不断提高您的算法能力,成为算法大师!