您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Path Sum

2015-10-11 16:45 507 查看

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.

For 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.

https://leetcode.com/problems/path-sum/

判断是否有一条从根到叶子的路径的和为sum。

如果不是叶子节点,递归进去,如果是叶子节点,计算路径是不是等于sum。

两道类似的题:

Binary Tree Paths : /article/7171000.html

Path Sum II : /article/7171042.html

/**
* Definition for a binary tree node.
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
var hasPathSum = function(root, sum) {
if(root && root.val !== undefined){
return hasSum(root, 0);
}
return false;

function hasSum(node, value){
var isLeaf = true, tmp;
if(node.left){
isLeaf = false;
tmp = hasSum(node.left, value + node.val);
if(tmp === true){
return true;
}
}
if(node.right){
isLeaf = false;
tmp = hasSum(node.right, value + node.val);
if(tmp === true){
return true;
}
}
if(isLeaf){
tmp = value + node.val;
if(tmp === sum){
return true;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: