返回

JavaScript实现:二叉树中查找从根节点到叶子节点的路径总和等于目标值的方法

前端

在计算机科学中,二叉树是一种非常重要的数据结构。它由一个根节点和零个或多个子节点组成,每个子节点又可以是二叉树。二叉树经常被用于表示各种各样的数据结构,比如集合、队列、栈、图等。

在二叉树中,从根节点到叶子节点的路径称为路径。路径上的所有节点值相加称为路径总和。给定一个二叉树和一个目标和,判断二叉树中是否存在从根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

这道题可以有两种方法来解决。第一种方法是使用深度优先搜索(DFS)来遍历二叉树。从根节点开始,每次都选择一条分支向下遍历。如果找到一条从根节点到叶子节点的路径,且路径总和等于目标和,那么返回true。否则,回溯到上一个节点,继续遍历其他分支。

第二种方法是使用广度优先搜索(BFS)来遍历二叉树。从根节点开始,将根节点加入队列。然后,每次从队列中取出一个节点,并将其子节点加入队列。重复这个过程,直到队列为空。如果在遍历过程中找到一条从根节点到叶子节点的路径,且路径总和等于目标和,那么返回true。否则,返回false。

下面是使用JavaScript实现的代码:

// Definition for a binary tree node.
function TreeNode(val, left, right) {
  this.val = (val===undefined ? 0 : val)
  this.left = (left===undefined ? null : left)
  this.right = (right===undefined ? null : right)
}

/**
 * Given a binary tree and a target sum, determine whether there is a path from the root to a leaf, such that the sum of the node values in the path equals the target sum.
 *
 * @param {TreeNode} root The root node of the binary tree.
 * @param {number} targetSum The target sum.
 * @return {boolean} True if there is a path from the root to a leaf, such that the sum of the node values in the path equals the target sum. Otherwise, return false.
 */
const hasPathSum = (root, targetSum) => {
  if (root === null) {
    return false;
  }

  if (root.left === null && root.right === null) {
    return root.val === targetSum;
  }

  return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
};

// Example usage:
const root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.left.right = new TreeNode(2);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);

const targetSum = 22;
const result = hasPathSum(root, targetSum);

console.log(`Has path sum to target sum: ${result}`);

输出结果为:

Has path sum to target sum: true