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 andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } Problem solving ideas: 1. Use dfs depth-first search, left - "root -" right 2. Judgment conditions for the main function to return to the exit 1) root==null (leaf node) 2) root.val==sum 3) The function returns naturally after executing the left and right nodes 3. Whether it satisfies sum==root.val or does not satisfy the function return, be sure to list.remove(list.size()-1); to delete the last number. 4. Every time you find a satisfied list, you need alllist.add(new ArrayList<Integer>(list)); it is more convenient to set the list allist as a global variable. */ import java.util.ArrayList; import java.util.List; public class Solution { ArrayList<Integer> list=new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> alllist=new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { if(root==null) return alllist; path(root, sum, list); return alllist; } public void path(TreeNode root, int sum,ArrayList<Integer> list) { if(root==null) return; list.add(root.val); if(root.left==null&root.right==null&&sum-root.val==0) { alllist.add(new ArrayList<Integer>(list)); list.remove(list.size()-1); return; } path(root.left, sum-root.val, list); path(root.right, sum-root.val, list); list.remove(list.size()-1); } }
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 andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]