上周六面试夏令营遇到相似的题了,一直在想非递归结果没做出来,递归一下就OK,好惨一同学😭。

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer>> we = new ArrayList<>();
    ArrayList<Integer> you = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        if(root == null){
            return we;
        }
        
        if(root.left == null && root.right == null){
            you.add(root.val);
            int sum = 0;
            for(Integer i : you){
                sum+=i;
            }
            if(sum == expectNumber){
                we.add(new ArrayList<>(you));
            }
            you.remove(you.size()-1);
            return we;
        }
        you.add(root.val);
        if(root.left !=null){
            FindPath(root.left,expectNumber);
        }
        
        if(root.right !=null){
            FindPath(root.right,expectNumber);
        }
        you.remove(you.size()-1);
        return we;
    }
}