HTMLify

LeetCode - Path Sum - Go
Views: 23 | Author: abh
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func pathSums(root *TreeNode, sum int) []int {
	var sums []int
	if root == nil {
		return sums
	}
	if root.Left == nil && root.Right == nil {
		sums = append(sums, sum + root.Val)
		return sums
	}
	sums = append(sums, pathSums(root.Left, sum + root.Val)...)
	sums = append(sums, pathSums(root.Right, sum + root.Val)...)
	return sums
}

func hasPathSum(root *TreeNode, targetSum int) bool {
	sums := pathSums(root, 0)
	for _, v := range sums {
		if v == targetSum {
			return true
		}
	}
	return false
}

Comments