题目描述
给定一个二叉树和一个值sum,请找出所有的根节点到叶子节点的节点值之和等于sum的路径,
例如:
给出如下的二叉树,sum=22,
5↵ / ↵ 4 8↵ / / ↵ 11 13 4↵ / / ↵ 7 2 5 1
返回
[↵ [5,4,11,2],↵ [5,8,4,5]↵]↵
代码
思路:这题遇到过很多次了,先序遍历
static ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();static ArrayList<Integer> arr = new ArrayList<Integer>();public static ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {if(root==null)return null;preOrder(root,sum,0);return list;}public static void preOrder(TreeNode root,int sum,int count) {if(root!=null) {count += root.val;arr.add(root.val);if(root.left==null&&root.right==null){if(count==sum) {list.add(new ArrayList<Integer>(arr));}}if(root.left!=null)preOrder(root.left, sum,count);if(root.right!=null)preOrder(root.right, sum,count);}arr.remove(arr.size()-1);}
