給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定如下二叉樹,以及目標和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/path-sum-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
相似問題:
思路:
回溯法+dfs,對樹進行前序遍歷,用中間數組t保存沿途路徑值,符合條件就加到結果數組res中:
代碼:
func pathSum(root *TreeNode, sum int) [][]int {
res := make([][]int,0)
if root == nil {
return res
}
t := make([]int,0)
run(root,sum,&res,t)
return res
}
func run(root *TreeNode,sum int,res *[][]int,t []int) {
if root == nil {
return
}
t = append(t,root.Val)
if root.Left == nil && root.Right == nil {
if sum-root.Val == 0 {
l := make([]int,len(t))
//這是根據go語言的特點,必須新開一個切片進行值複製
//要不然將原切片t放到res中,後續遍歷結果也會修改res的值
copy(l,t)
*res = append(*res,l)
}
return
}
run(root.Left,sum-root.Val,res,t)
run(root.Right,sum-root.Val,res,t)
}
注意:
用go切片是一個引用類型。