4
头图

A path whose sum is a certain value in a binary tree

Title description

Input the root node of a binary tree and an integer, and print out all the paths where the sum of the node values in the binary tree is the input integer in lexicographic order. The path is defined as a path from the root node of the tree and going down to the nodes passed by the leaf nodes.

title link : binary tree neutralization path

Code

import java.util.ArrayList;

/**
 * 标题:二叉树中和为某一值的路径
 * 题目描述
 * 输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 * 题目链接:
 * https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&&tqId=11177&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz24 {

    private static ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();

    public static ArrayList<ArrayList<Integer>> findPath(TreeNode root, int target) {
        backtracking(root, target, new ArrayList<>());
        return ret;
    }

    /**
     * 回溯法
     *
     * @param node
     * @param target
     * @param path
     */
    private static void backtracking(TreeNode node, int target, ArrayList<Integer> path) {
        if (node == null) {
            return;
        }
        path.add(node.val);
        target -= node.val;
        if (target == 0 && node.left == null && node.right == null) {
            ret.add(new ArrayList<>(path));
        } else {
            backtracking(node.left, target, path);
            backtracking(node.right, target, path);
        }
        path.remove(path.size() - 1);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        for (ArrayList<Integer> integers : findPath(root, 3)) {
            for (Integer integer : integers) {
                System.out.print(integer + " ");
            }
            System.out.println();
        }
    }
}
[Daily Message] The road ahead is vast, and everything can be expected.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!