📑 题目:112. 路径总和

🚀 本题 LeetCode 传送门

题目大意

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

解题思路

  • 递归求解即可

代码

  1. package leetcode
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. func hasPathSum(root *TreeNode, sum int) bool {
  11. if root == nil {
  12. return false
  13. }
  14. if root.Left == nil && root.Right == nil {
  15. return sum == root.Val
  16. }
  17. return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val)
  18. }