JZ24-二叉树中和为某一值的路径

二叉树中和为某一值的路径

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey

class Solution {
    ArrayList<ArrayList<Integer>> out = new ArrayList<>();

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
        if (root == null) {
            return out;
        }
        backtracking(root, target, new ArrayList<>());
        return out;
    }

    public void backtracking(TreeNode root, int target, ArrayList<Integer> in) {
        if (root == null) {
            return;
        }
        in.add(root.val);
        target -= root.val;
        if (target == 0 && root.left == null && root.right == null) {
            out.add(new ArrayList<>(in));  //ArrayList<ArrayList<Integer> in>
        } else {
            backtracking(root.left, target, in);//回溯法,分别尝试不同方向
            backtracking(root.right, target, in);
        }
        in.remove(in.size() - 1);
        // 8 9 2 4 -> 8 9 2 1(把2的左子树4删去,重新加上1)
        //代码走到这里,表明要回溯,代表当前path中的root节点我已经不需要了
    }
}

全部评论

相关推荐

09-22 18:09
门头沟学院 C++
点赞 评论 收藏
分享
昨天 16:38
中南大学 营销
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务