牛客网刷题(JAVA) 25:二叉树中和为某一值的路径

难度系数 ⭐⭐⭐难在思路

时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

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

思路 递归遍历,在每一次深入遍历时,目标数值将会变化,即目标数值-当前数值,若遍历至叶子节点,且此时目标数值变化为0,则该路径即为待查找的路径。

package nowcoder;

import java.util.ArrayList;

public class No26 {
    private ArrayList<ArrayList<Integer>> res = new ArrayList<>();
    private ArrayList<Integer> path = new ArrayList<>();

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

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

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
        if (root == null) return res;
        target -= root.val;
        path.add(root.val);
        if (root.left == null && root.right == null && target == 0)
            res.add(new ArrayList<Integer>(path));  // 若写作res.add(path),最终res中的path将不会有数值

        if (root.left != null) res = FindPath(root.left, target);
        if (root.right != null) res = FindPath(root.right, target);

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

        return res;
    }

    public static void main(String[] args){
        TreeNode head = new TreeNode(1);
        head.left = new TreeNode(2);
        head.right = new TreeNode(3);
        head.left.left = new TreeNode(4);
        head.left.right = new TreeNode(5);
        head.right.left = new TreeNode(6);
        head.right.right = new TreeNode(7);
        head.right.right.right = new TreeNode(8);

//        System.out.println(FindPath(head, 8));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值