mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #2609 from markwang1992/112-hasPathSum
112.路径总和增加Go递归法
This commit is contained in:
@ -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 {
|
||||
|
Reference in New Issue
Block a user