Lintcode1357.Path Sum II go

/**
1357 · Path Sum II
Algorithms
Medium
Accepted Rate
78%

DescriptionSolutionNotesDiscussLeaderboard
Description
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

A leaf is a node with no children.

Example
Example 1:

Input: root = {5,4,8,11,#,13,4,7,2,#,#,5,1}, sum = 22
5
/
4 8
/ /
11 13 4
/ \ /
7 2 5 1
Output: [[5,4,11,2],[5,8,4,5]]
Explanation:
The sum of the two paths is 22:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
Example 2:

Input: root = {10,6,7,5,2,1,8,#,9}, sum = 18
10
/
6 7
/ \ /
5 2 1 8
\
9
Output: [[10,6,2],[10,7,1]]
Explanation:
The sum of the two paths is 18:
10 + 6 + 2 = 18
10 + 7 + 1 = 18

https://blog.csdn.net/u011809767/article/details/77102405?utm_source=blogkpcl8
https://www.jianshu.com/p/8dbe00d52865

https://www.lintcode.com/problem/1357/
*/

参考有个老哥的解法写了一个go语言的,但是没过,有时间改一下。

//WA
func pathSum(root *TreeNode, sum int) [][]int {
	// Write your code here.
	var res [][]int
	var re []int
	dfs(root, &res, &re, sum)
	return res
}

func dfs(root *TreeNode, res *[][]int, re *[]int, sum int) {
	if root == nil {
		return;
	}
	if root.Val == sum && root.Left == nil && root.Right == nil {
		*re = append(*re, root.Val)
		*res = append(*res, *re)
		*re = (*re)[:len(*re) - 1]
		return;
	}
	re1 := append(*re, root.Val)
	dfs(root.Left, res, &re1, sum - root.Val)
	re2 := append(*re, root.Val)
	dfs(root.Right, res, &re2, sum - root.Val)
}

下面转载下另一个老哥的正确的版本,是AC的

public List<List<Integer>> pathSum2(TreeNode root, int sum) {
        List<Integer> out = new ArrayList<Integer>();
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        pathSum2Helper(root, sum, out, res);
        return res;
    }

    public void pathSum2Helper(TreeNode root, int sum, List<Integer> out, List<List<Integer>> res) {
        if (root == null) {
            return;
        }

        int val = root.val;

        if (val == sum && root.left == null && root.right == null) {
            out.add(val);
            res.add(new ArrayList<Integer>(out));
            out.remove(out.size() - 1);
            return;
        }
        out.add(val);
        pathSum2Helper(root.left, sum - val, out, res);
        pathSum2Helper(root.right, sum - val, out, res);
        out.remove(out.size() - 1);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值