LeetCode113 路径和2

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

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

  5
 / \
4   8

/ /
11 13 4
/ \ /
7 2 5 1
Return:

[
[5,4,11,2],
[5,8,4,5]
]

public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        List<Integer> cur = new LinkedList<Integer>();
        helper(root,sum,cur,ans);
        return ans;
    }
    public void helper(TreeNode root,int sum,List<Integer> cur,List<List<Integer>> ans){
        if(root == null) return;
        cur.add(root.val);
        if(root.left == null && root.right == null && root.val == sum){
            ans.add(new LinkedList(cur));
            cur.remove(cur.size() - 1);
            return;
        }else{
            helper(root.left, sum - root.val, cur, ans);
		    helper(root.right, sum - root.val, cur, ans);
        }
        cur.remove(cur.size() - 1);
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85401668