The binary tree of the sword finger and the path of a certain value

Keywords: Java

Input the following node and an integer of a binary tree, and print out all paths in which the sum of node values in the binary tree is the input integer. Path is defined as a path from the root node of the tree to the node that the leaf node passes through. (Note: in the list of returned values, the array with large array length is first)

/**
The idea of this problem is to store the data of each traversal through recursive first order traversal, and then when it reaches the leaf node,
Judge its sum, if it is, save it, then return to the parent node, and transfer the current node from the
Delete in path
*/

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>> lists = new ArrayList<>();
        if(root==null)
            return lists;
		Stack<Integer> stack = new Stack<>();
		findPath(root, target, 0, stack, lists);
		return lists;
    }
   public void findPath(TreeNode root, int target, int currentSum, Stack<Integer> stack,
			ArrayList<ArrayList<Integer>> lists) {
		currentSum += root.val;
		stack.push(root.val);
		if (root.left == null && root.right == null && currentSum == target) {
			int sum = 0;
			ArrayList<Integer> list = new ArrayList<>();
			for (int i = 0; i < stack.size(); i++) {

				list.add(stack.get(i));
			}
			lists.add(list);
		}
		if (root.left != null)// When the left subtree is not empty, look for the left subtree
			findPath(root.left, target, currentSum, stack, lists);
		if (root.right != null)// When the right subtree is not empty, look for the right subtree
			findPath(root.right, target, currentSum, stack, lists);
		// When returning to the parent node, delete the current node on the path
		stack.pop();

	}
}

Posted by gordsmash on Sun, 24 Nov 2019 06:58:50 -0800