1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| package main
import ( "fmt" )
type TreeNode struct { Data int Left *TreeNode Right *TreeNode }
func FindPath(root *TreeNode, sum int) { if root == nil || root.Data == 0 || root.Left == nil || root.Right == nil { return }
var path []int cursum := 0 findPath(root, sum, path, cursum) fmt.Println("------") fmt.Println(path) fmt.Println(cursum) }
func findPath(root *TreeNode, sum int, path []int, cursum int) { cursum += root.Data path = append(path, root.Data)
leaf := root.Left == nil && root.Right == nil if cursum == sum && leaf { fmt.Print("a path is found: ") for i := 0; i < len(path); i++ { fmt.Printf("%d --> ", path[i]) } fmt.Println() }
if root.Left != nil { findPath(root.Left, sum, path, cursum) } if root.Right != nil { findPath(root.Right, sum, path, cursum) }
cursum -= root.Data path = path[:len(path)-1] fmt.Println(cursum) fmt.Println(path) }
func main() { node4 := &TreeNode{4, nil, nil} node7 := &TreeNode{7, nil, nil} node5 := &TreeNode{5, node4, node7} node12 := &TreeNode{12, nil, nil} node10 := &TreeNode{10, node5, node12} FindPath(node10, 22) }
19 [10 5 4] a path is found: 10 --> 5 --> 7 --> 22 [10 5 7] 15 [10 5] a path is found: 10 --> 12 --> 22 [10 12] 10 [10] ------ [] 0
Process finished with exit code 0
|