mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
112.路径总和增加Go递归法
This commit is contained in:
@ -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 {
|
||||||
|
Reference in New Issue
Block a user