Merge pull request #2609 from markwang1992/112-hasPathSum

112.路径总和增加Go递归法
This commit is contained in:
程序员Carl
2024-08-11 09:52:58 +08:00
committed by GitHub

View File

@ -727,6 +727,48 @@ class Solution:
```go
//递归法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
return traversal(root, targetSum - root.Val)
}
func traversal(cur *TreeNode, count int) bool {
if cur.Left == nil && cur.Right == nil && count == 0 {
return true
}
if cur.Left == nil && cur.Right == nil {
return false
}
if cur.Left != nil {
count -= cur.Left.Val
if traversal(cur.Left, count) {
return true
}
count += cur.Left.Val
}
if cur.Right != nil {
count -= cur.Right.Val
if traversal(cur.Right, count) {
return true
}
count += cur.Right.Val
}
return false
}
```
```go
//递归法精简
/**
* Definition for a binary tree node.
* type TreeNode struct {