From 423ed9899e4a7400eaade4abaa270ff1548d9079 Mon Sep 17 00:00:00 2001 From: markwang Date: Thu, 11 Jul 2024 09:05:30 +0800 Subject: [PATCH] =?UTF-8?q?112.=E8=B7=AF=E5=BE=84=E6=80=BB=E5=92=8C?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Go=E9=80=92=E5=BD=92=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 2beb8a7f..6709a2fb 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -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 {