File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff 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 {
You can’t perform that action at this time.
0 commit comments