欢迎光临散文网 会员登陆 & 注册

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

2023-07-14 01:20 作者:Acer在写代码  | 我要投稿

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]

}

二叉树基础题难倒大厂程序员,我的粉丝都会写吧的评论 (共 条)

分享到微博请遵守国家法律