1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package main
import "fmt"
type TreeNode struct { Val int Left *TreeNode Right *TreeNode }
func hasPathSum(root *TreeNode, targetSum int) bool { if root == nil { return false }
if root.Left == nil && root.Right == nil { return targetSum == root.Val }
return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val) }
func main() { root := &TreeNode{Val: 5} root.Left = &TreeNode{Val: 4} root.Right = &TreeNode{Val: 8} root.Left.Left = &TreeNode{Val: 11} root.Left.Left.Left = &TreeNode{Val: 7} root.Left.Left.Right = &TreeNode{Val: 2} root.Right.Left = &TreeNode{Val: 13} root.Right.Right = &TreeNode{Val: 4} root.Right.Right.Right = &TreeNode{Val: 1}
targetSum := 22
result := hasPathSum(root, targetSum)
fmt.Printf("是否存在路径和为 %d 的路径: %v\n", targetSum, result) }
|