剑指offer 34 二叉树中和为某一值的路径 Java

public class BinaryTreePath34_ {
    static class Node {
        int val;
        Node left;
        Node right;

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

        @Override
        public String toString() {
            return "Node{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }

    public static void main(String[] args) {
        Node root = new Node(8);
        Node node21 = new Node(6);
        Node node22 = new Node(10);
        Node node31 = new Node(15);
        Node node32 = new Node(7);
        Node node33 = new Node(9);
        Node node34 = new Node(11);
        root.left = node21;
        root.right = node22;
        node21.left = node31;
        node21.right = node32;
        node22.left = node33;
        node22.right = node34;
        paths(root, 29, new ArrayList<>());
        for (int i = 0; i < result.size(); i++) {
            for (int j = 0; j < result.get(i).size(); j++) {
                System.out.print(result.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }

    static List<ArrayList<Integer>> result = new ArrayList<>();


    private static void paths(Node root, int target, List<Integer> path) {
        //递归截止条件
        if (root == null)
            return;
        path.add(root.val);
        target -= root.val;
        //如果路径和满足条件并且是叶子节点,把路径添加到result
        if (target == 0 && root.left == null && root.right == null) {
            result.add(new ArrayList<>(path));
        } else {
            paths(root.left, target, path);
            paths(root.right, target, path);
        }
        path.remove(path.size() - 1);
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_43065507/article/details/99328446
今日推荐