-
Notifications
You must be signed in to change notification settings - Fork 46
Open
Description
/**
* 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 === null){
return false;
}
if(root.left === null && root.right === null){
return sum -root.val === 0;
}
return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
};
解题思路:在递归遍历的过程中,对于每个节点来说。sum减去本节点的val值之后的值作为子节点的sum,如果sum为零时正好到达叶子节点。那说明存在这样的一条路径。
leetcode原题地址:https://leetcode-cn.com/problems/path-sum/description/