Skip to content

路径总和(I、II、III) #8

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

Open
funnycoderstar opened this issue Aug 23, 2018 · 0 comments
Open

路径总和(I、II、III) #8

funnycoderstar opened this issue Aug 23, 2018 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Aug 23, 2018

JavaScript实现LeetCode第112题:路径总和

题目描述

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

说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22

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

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

思路

深度优先搜索

  1. 任何一个节点开始,首先判断是否空节点。空就返回false。
  2. 判断是否叶子节点。是的话判断是否符合题给条件。符合则返回true。否则返回false。

方案

/**
 * 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;
    }
    let left = root.left;
    let right = root.right;
    if (left === null && right === null) {
        return root.val === sum;
    }
    return hasPathSum(left, sum - root.val) || hasPathSum(right, sum - root.val);
};
@funnycoderstar funnycoderstar changed the title 112. 路径总和 路径总和(I、II、III) Apr 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant