import java.util.ArrayList;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
ArrayList<ArrayList<Integer>> arr=new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<Integer>list=new ArrayList<>();
getPaths(root,sum,list);
return arr;
}
//递归函数实现路径存储
public void getPaths(TreeNode root,int sum,ArrayList<Integer>list){
if(root==null) return;
if(root.left==null&&root.right==null&&sum-root.val==0){
list.add(root.val);
arr.add(new ArrayList<Integer>(list));
list.remove(list.size()-1);
return;
}
list.add(root.val);
getPaths(root.left,sum-root.val,list);
getPaths(root.right,sum-root.val,list);
list.remove(list.size()-1);
}
public static void main(String[]args){
//System.out.println("Hello World!");
}
}
给定值,寻找二叉树中满足的所有路径
最新推荐文章于 2023-08-03 10:48:50 发布