Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

112. Path Sum #248

Open
Tcdian opened this issue Jul 7, 2020 · 1 comment
Open

112. Path Sum #248

Tcdian opened this issue Jul 7, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jul 7, 2020

112. Path Sum

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

Note

  • 叶子节点是指没有子节点的节点。

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.

@Tcdian
Copy link
Owner Author

Tcdian commented Jul 7, 2020

Solution

  • JavaScript Solution
/**
 * 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} sum
 * @return {boolean}
 */
var hasPathSum = function(root, sum) {
    let accumVal = 0;
    let result = false;
    dfs(root);
    return result;

    function dfs(root) {
        if (root === null || result) {
            return;
        }
        accumVal += root.val;
        if (accumVal === sum && root.left === null && root.right === null) {
            result = true;
            return;
        }
        dfs(root.left);
        dfs(root.right);
        accumVal -= root.val;
    }
};
  • TypeScript Solution
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function hasPathSum(root: TreeNode | null, sum: number): boolean {
    let accumVal = 0;
    let result = false;
    dfs(root);
    return result;

    function dfs(root: TreeNode | null) {
        if (root === null || result) {
            return;
        }
        accumVal += root.val;
        if (accumVal === sum && root.left === null && root.right === null) {
            result = true;
            return;
        }
        dfs(root.left);
        dfs(root.right);
        accumVal -= root.val;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant