二叉树中和为某一值的路径

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.ArrayList;
import java.util.Stack;


public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ArrayList<ArrayList<Integer>> findPath(TreeNode root,int target){
        ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
        if(root == null){
            return pathList;
        }
        Stack<Integer> stack = new Stack<Integer>();
        findPath(root, target, stack, pathList);
        return pathList;
    }
   
    private void findPath(TreeNode root, int target, Stack<Integer> path, ArrayList<ArrayList<Integer>> pathList) {
        if(root == null)
            return;
           
        if(root.left == null && root.right == null){
            if(root.val == target){
                ArrayList<Integer> ValList = new ArrayList<Integer>();
                for(int i : path){
                    ValList.add(i);
                }
                ValList.add(root.val);
                pathList.add(ValList);
            }
        } else {
            path.push(new Integer(root.val));
            findPath(root.left, target-root.val, path, pathList);
            findPath(root.right, target-root.val, path,  pathList);
            path.pop();
        }
    }
}