Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
求二叉树是否存在一条路径(根-子叶)所有节点的值加起来等于目标值
- Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
- 解法一,递归
var hasPathSum = function(root, sum) {
if(!root) return false;
let newSum = sum - root.val
if(!root.left && !root.right){return newSum === 0}
return hasPathSum(root.left,newSum) || hasPathSum(root.right,newSum)
};
- 解法二,递归
function hasPathsum(root,sum){
let result = false;
const add = (node, total=0) =>{
if(!node) return false;
let currentVal = total + node.val;
if(!node.left && !node.right && currentVal === sum){
return true
}
add(node.left,currentVal)
add(node.right,currentVal)
}
add(root)
return result
}