Skip to content

112两数和

code

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
var hasPathSum = function(root, targetSum) {
    function test(root, target) {
        if(root === null){
            return false;
        }
        if(root.left === null && root.right === null){
            if(root.val === target) {
                return true;
            }
            return false;
        }
        return test(root.left, (target - root.val)) || test(root.right, (target - root.val));
    }
    return test(root, targetSum);
};

总结

  1. 我觉得还好,并并正负那些就行,其实感觉二叉树类的东西好弄,左递归右递归就好了