Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 423ed98

Browse files
112.路径总和增加Go递归法
1 parent 4f9c892 commit 423ed98

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎problems/0112.路径总和.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,48 @@ class Solution:
727727

728728
```go
729729
//递归法
730+
/**
731+
* Definition for a binary tree node.
732+
* type TreeNode struct {
733+
* Val int
734+
* Left *TreeNode
735+
* Right *TreeNode
736+
* }
737+
*/
738+
func hasPathSum(root *TreeNode, targetSum int) bool {
739+
if root == nil {
740+
return false
741+
}
742+
return traversal(root, targetSum - root.Val)
743+
}
744+
745+
func traversal(cur *TreeNode, count int) bool {
746+
if cur.Left == nil && cur.Right == nil && count == 0 {
747+
return true
748+
}
749+
if cur.Left == nil && cur.Right == nil {
750+
return false
751+
}
752+
if cur.Left != nil {
753+
count -= cur.Left.Val
754+
if traversal(cur.Left, count) {
755+
return true
756+
}
757+
count += cur.Left.Val
758+
}
759+
if cur.Right != nil {
760+
count -= cur.Right.Val
761+
if traversal(cur.Right, count) {
762+
return true
763+
}
764+
count += cur.Right.Val
765+
}
766+
return false
767+
}
768+
```
769+
770+
```go
771+
//递归法精简
730772
/**
731773
* Definition for a binary tree node.
732774
* type TreeNode struct {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /