leetcode --- js版本

leetcode-tree-112- Path Sum

2019-06-17  本文已影响1人  石头说钱

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.
求二叉树是否存在一条路径(根-子叶)所有节点的值加起来等于目标值


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
}
上一篇下一篇

猜你喜欢

热点阅读