112.路径总和增加Go递归法

This commit is contained in:
markwang
2024-07-11 09:05:30 +08:00
parent 4f9c8920ab
commit 423ed9899e

View File

@ -727,6 +727,48 @@ class Solution:
```go ```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. * Definition for a binary tree node.
* type TreeNode struct { * type TreeNode struct {