有人可以帮助我使用路径2吗?
在LeetCode
鉴于二进制树和整数靶标的根,返回所有根到叶路径,其中路径中的节点值等于靶标。每个路径应作为节点值的列表返回,而不是节点引用。 根到叶的路径是从根开始并在任何叶节点结束的路径。叶是一个没有孩子的节点。
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
输入: root = [5,4,8,11,null,13,4,7,2,null,null,null,null,null,null, 5,1]
,targetsum = 22
预期输出: [[5,4,11,2],[5,8,4, 5]]
说明:有两条路径等于目标:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 4 + 5 = 22
实际输出:< /strong> [[5,4,11,2],[5,8,4,1]]
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) [][]int {
result := [][]int{}
findPaths(root, targetSum, []int{}, &result)
return result
}
func findPaths(root *TreeNode, sum int, path []int, result *[][]int) {
if root == nil {
return
}
path = append(path, root.Val)
if root.Left == nil && root.Right == nil && root.Val == sum {
fmt.Println("adding new path",path)
*result = append(*result, path)
return
}
findPaths(root.Left, sum-root.Val, path, result)
findPaths(root.Right, sum-root.Val, path, result)
}
stdoutput:
adding new path [5 4 11 2]
adding new path [5 8 4 5]
need a little help with leetcode path sum 2 problem.
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1]
, targetSum = 22
Expected Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
Actual Output: [[5,4,11,2],[5,8,4,1]]
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) [][]int {
result := [][]int{}
findPaths(root, targetSum, []int{}, &result)
return result
}
func findPaths(root *TreeNode, sum int, path []int, result *[][]int) {
if root == nil {
return
}
path = append(path, root.Val)
if root.Left == nil && root.Right == nil && root.Val == sum {
fmt.Println("adding new path",path)
*result = append(*result, path)
return
}
findPaths(root.Left, sum-root.Val, path, result)
findPaths(root.Right, sum-root.Val, path, result)
}
StdOutput:
adding new path [5 4 11 2]
adding new path [5 8 4 5]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论