二叉树中和为某一值的路径 (java)
问题描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
题解
1 import java.util.ArrayList; 2 /** 3 public class TreeNode { 4 int val = 0; 5 TreeNode left = null; 6 TreeNode right = null; 7 8 public TreeNode(int val) { 9 this.val = val; 10 11 } 12 13 } 14 */ 15 public class Solution { 16 public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { 17 ArrayList<ArrayList<Integer>> arrayLists=new ArrayList<>(); 18 ArrayList<Integer> arrayList=new ArrayList<>(); 19 if(root==null) 20 return arrayLists; 21 int sum=0; 22 return FindPath(root,sum,target,arrayLists,arrayList); 23 } 24 25 private ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int sum,int target,ArrayList<ArrayList<Integer>> arrayLists,ArrayList<Integer> arrayList){ 26 sum+=root.val; 27 arrayList.add(root.val); 28 boolean isLeafNode=root.left==null&&root.right==null; 29 if(isLeafNode){ 30 if(sum==target){ 31 ArrayList tmpList=new ArrayList(); 32 tmpList.addAll(arrayList); 33 arrayLists.add(tmpList); 34 } 35 } 36 if(root.left!=null){ 37 arrayLists=FindPath(root.left,sum,target,arrayLists,arrayList); 38 } 39 if(root.right!=null){ 40 arrayLists=FindPath(root.right,sum,target,arrayLists,arrayList); 41 } 42 arrayList.remove(arrayList.size()-1); 43 return arrayLists; 44 } 45 }