29.二叉树中和为某一值的路径(二)

题目:输入一颗二叉树的根节点root和一个整数expectNumber,找出二叉树中结点值的和为expectNumber的所有路径。和(一)的区别就是在于输出方式的区别。

import java.util.*;
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 {
    private ArrayList> res = new ArrayList>();
    public ArrayList> FindPath(TreeNode root,int expectNumber) {
        ArrayList list  = new ArrayList();
        FindPath(root,list,expectNumber);
        return res;
        
    }
    public void FindPath(TreeNode node,ArrayList list,int expectNumber){
        if(node == null) return;
        list.add(node.val);
        expectNumber = expectNumber-node.val;
        if(expectNumber == 0 && node.left == null && node.right == null){
            res.add(new ArrayList(list));
        }
        FindPath(node.left,list,expectNumber);
        FindPath(node.right,list,expectNumber);
        list.remove(list.size()-1);
    };
}

你可能感兴趣的:(数据结构)