Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:112. 路径总和,递归,JavaScript,详细注释 #453

Open
chencl1986 opened this issue May 23, 2024 · 0 comments
Open

Comments

@chencl1986
Copy link
Owner

原题链接:

112. 路径总和

解题思路:

  1. 如果求根节点到叶子节点的路径上的节点值之和,假设共有3个节点,那么写成计算式是val1 + val2 + val3 = sum
  2. 那么将计算式转换就可以得到val3 = sum - val1 - val2
  3. 也就是说,问题可以从求和转换为,每向下查找一层节点,就将求和减去当前节点的值,最后只要判断叶子节点的值val3,是否和最后sum - val1 - val2相等即可
  4. 需要特别判断的是:二叉树为空,此时无值,返回false
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
var hasPathSum = function(root, targetSum) {
  // 如果二叉树为空
  if (!root) return false
  // 如果当前节点没有子节点,它就是叶子节点,只要判断root.val === targetSum
  if (!root.left && !root.right) return root.val === targetSum

  // 每一层节点都将targetSum减去root.val,最后一层只要对比叶子节点的值是否等于targetSum
  // 最后将结果逐层向上返回
  return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant