二叉树基础题难倒大厂程序员,我的粉丝都会写吧

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
}
//选择这个节点
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]
}