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. 路径总和 #41

Open
yankewei opened this issue Jul 7, 2020 · 0 comments
Open

112. 路径总和 #41

yankewei opened this issue Jul 7, 2020 · 0 comments
Labels
深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Jul 7, 2020

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

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

示例:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum

解答

深度优先搜索(DFS)

既然题目问的是有没有从根节点到叶子节点的总和有没有等于目标值得,那我们就把所有路径尝试即可。

func hasPathSum(root *TreeNode, sum int) bool {
    if root == nil {
        return false
    }
    if root.Left == nil && root.Right == nil {
        return sum == root.Val
    }
    return hasPathSum(root.Left, sum - root.Val) || hasPathSum(root.Right, sum - root.Val)
}
@yankewei yankewei added 简单 题目难度为简单 深度优先搜索 题目包含深度优先搜索解法 labels Jul 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant