二叉樹基礎(chǔ)題難倒大廠程序員,我的粉絲都會(huì)寫吧

golang版本
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 遞歸解決
var res [][]int
func pathSum(root *TreeNode, target int) [][]int {
if root == nil {
return nil
}
res = [][]int{}
recurPath(target, root, []int{})
return res
}
func recurPath(target int, root *TreeNode, pb []int) {
if root == nil {
return
}
//選擇這個(gè)節(jié)點(diǎn)
pb = append(pb, root.Val)
//截止條件
if root.Left == nil && root.Right == nil && root.Val == target {
res = append(res, append([]int{}, pb...))
return
}
recurPath(target-root.Val, root.Left, pb)
recurPath(target-root.Val, root.Right, pb)
pb=pb[:len(pb)-1]
}
標(biāo)簽: