给定一个二叉树和一个和,找到所有从根到叶路径总和等于给定总和的路径。
例如,
给定下面的二叉树和 sum = 22,
5
/
4 8
/ /
11 13 4
/ /
7 2 5 1
返回
[
[5,4,11,2],
[5,8,4,5]
]
详见:https://leetcode.com/problems/path-sum-ii/description/
Java实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res=new ArrayList<List<Integer>>(); if(root==null){ return res; } helper(root,sum,new ArrayList<Integer>(),res); return res; } private void helper(TreeNode root,int sum,ArrayList<Integer> path,List<List<Integer>> res){ if(root==null){ return; } path.add(root.val); if(root.val==sum&&root.left==null&&root.right==null){ res.add(new ArrayList<Integer>(path)); }else{ helper(root.left,sum-root.val,path,res); helper(root.right,sum-root.val,path,res); } path.remove(path.size()-1); } }
python实现: