leetCode打卡——[112] Path Sum

155 阅读1分钟

题目

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.

Example:

Given the below binary tree and sum = 22,

  5
 / \
4   8
/   / \
11  13  4
/  \      \
7    2      1

思路

  1. 在树上寻找路径,一般采用递归的方式实现;
  2. 一个树是否存在题意的路径,可以分解成左右子树是否存在和为sum - root.val的路径;
  3. 当当前节点是叶子节点,则判断该叶子节点的值是否跟传入的需求总和相等,否则继续递归;
var hasPathSum = function(root, sum) {
    return run(root, sum);
};

var run = function(node, sum) {
    if (!node) return false;

    if (isLeaf(node)) {
        return node.val === sum;
    } else {
        return run(node.left, sum - node.val) || run(node.right, sum - node.val);
    }
}

var isLeaf = function(node) {
    return !node.left && !node.right;
}