The sword refers to the path in the binary tree of the offer that sums to a certain value

Question: Input a binary tree and an integer, print out all paths in the binary tree whose sum of node values ​​is the input integer. A path is formed from the root node of the tree down to the nodes passed by the leaf nodes.

import java.util.ArrayList;

public class FindPath {
    ArrayList<Integer> path = new ArrayList<>();
    ArrayList<ArrayList<Integer>> list = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> findPath(TreeNode root,int target) {
        if (root==null){
            return list;
        }
        path.add(root.val);
        target = target- root.val;
        if(target==0 && root.left==null && root.right == null){
            list.add(new ArrayList<Integer>(path));

        }
        findPath(root.left, target);
        findPath(root.right, target);

        path.remove(path.size()-1);
        return list;

    }

    public static void main(String[] args) {
        TreeNode a = new TreeNode(0);
        TreeNode b = new TreeNode(1);
        TreeNode c = new TreeNode(2);
        TreeNode d = new TreeNode(3);
        TreeNode e = new TreeNode(4);
        TreeNode f = new TreeNode(5);
        TreeNode g = new TreeNode(6);
        a.left=b;
        a.right=c;
        b.left=d;
        b.right=e;
        c.left=f;
        c.right=g;
        FindPath find = new FindPath();
        ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
        list = find.findPath(a, 7);
        for( ArrayList<Integer> path:list ){
            for(Integer item: path){
                System.out.print(item +" ");
            }
            System.out.println();
        }

    }

}

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324731319&siteId=291194637
Recommended