66 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {boolean}
*/
const hasPathSum = function (root, targetSum) {
};
/*
思路:利用递归抽象问题,如果左节点或者右节点满足 targetSum - root.val那么整个树就满足
*/
function f1(root, targetSum) {
if (!root) return false; // 如果当前节点为空,返回 false
// 如果当前节点是叶子节点,且值等于目标值,返回 true
if (!root.left && !root.right) return root.val === targetSum;
// 递归判断左子树或右子树是否存在满足条件的路径
const remainingSum = targetSum - root.val;
return hasPathSum(root.left, remainingSum) || hasPathSum(root.right, remainingSum);
}
/*
思路:利用层序遍历,获得从根节点到当前节点的所有和,只需准备两个队列,一个队列用于层序遍历,一个节点用于保存层序遍历到的
每一个值得路径综合如果这个节点是一个叶子节点就检查总和是不是和targetSum一致如果不一致继续检查其他得叶子节点
*/
function f2(root, targetSum) {
if (!root) return false; // 如果根节点为空直接返回false
const nodeQue = [root]; // 层序遍历的队列
const sumQue = [root.val]; // 遍历nodeQue的节点的路径总和和nodeQue是同步的
while (nodeQue.length > 0) {
const node = nodeQue.shift();
const sum = sumQue.shift();
// 如果当前节点为叶子节点检查sum是否和targetSum相等
if (!node.left && !node.right && sum === targetSum) return true;
// 如果左右节点存在将左右节点存入队列对应的路径和存入sum队列
if (node.left) {
nodeQue.push(node.left);
sumQue.push(sum + node.left.val);
}
if (node.right) {
nodeQue.push(node.right);
sumQue.push(sum + node.right.val);
}
}
return false;
}
/*
思路三和f1是一样的只不过利用dfs来代替递归//TODO
*/