pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

路径总和 #1040

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

112. 路径总和

/**
 * 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;
    return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
};