Created
September 15, 2018 02:24
-
-
Save yojkim/cfdbc07648cb7807c83ec189605c1c2b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* type TreeNode struct { | |
* Val int | |
* Left *TreeNode | |
* Right *TreeNode | |
* } | |
*/ | |
func searchTree(node *TreeNode, sum int, target int) [][]int { | |
var left [][]int | |
var right [][]int | |
var temp []int | |
var final = [][]int{} | |
if node.Left == nil && node.Right == nil { | |
if sum == target { | |
return [][]int{{node.Val}} | |
} | |
} | |
if node.Left != nil { | |
left = searchTree(node.Left, sum + node.Left.Val, target) | |
} | |
if node.Right != nil { | |
right = searchTree(node.Right, sum + node.Right.Val, target) | |
} | |
if left != nil { | |
for _, arr := range left { | |
temp = append([]int{node.Val}, arr...) | |
final = append(final, temp) | |
} | |
} | |
if right != nil { | |
for _, arr := range right { | |
temp = append([]int{node.Val}, arr...) | |
final = append(final, temp) | |
} | |
} | |
if len(final) == 0 { | |
return nil | |
} else { | |
return final | |
} | |
} | |
func pathSum(root *TreeNode, sum int) [][]int { | |
if root == nil { | |
return nil | |
} | |
return searchTree(root, root.Val, sum) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment