[leedcode 113] Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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] ]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<List<Integer>> res; List<Integer> seq; public List<List<Integer>> pathSum(TreeNode root, int sum) { //本题求的是中间结果,需要构造一个函数,函数参数sum表示sum-当前已经遍历过的和,递归终止条件:当遍历到叶子节点, //和为0时,添加结果。注意遍历完左节点和右节点之后,不要忘记弹出最近放入的节点 res=new ArrayList<List<Integer>>(); seq=new ArrayList<Integer>(); if(root==null) return res; getPath(root,sum); return res; } public void getPath(TreeNode root,int sum){ if(root==null) return; seq.add(root.val); if(root.left==null&&root.right==null&&(sum-root.val==0)){ res.add(new ArrayList<Integer>(seq)); } getPath(root.left,sum-root.val); getPath(root.right,sum-root.val); seq.remove(seq.size()-1);////*** } }