题解 | #二叉树中和为某一值的路径(二)# 递归

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

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    ArrayList<ArrayList<Integer>> resultArr = new ArrayList<>();
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param target int整型
     * @return int整型ArrayList<ArrayList<>>
     */
    void findSumEqualWay(TreeNode root, int sum, ArrayList<Integer> path,
                         int target) {
        ArrayList<Integer> tarr = new ArrayList<>(path);
        if (root == null) return;
        sum += root.val;
        tarr.add(root.val);
        if (target == sum && root.left == null && root.right == null) {
            resultArr.add(tarr);
        }
        // 左子树查询
        findSumEqualWay(root.left, sum, tarr, target);
        // 右子树查询
        findSumEqualWay(root.right, sum, tarr, target);

    }
    public ArrayList<ArrayList<Integer>> FindPath (TreeNode root, int target) {
        // write code here
        findSumEqualWay(root, 0, new ArrayList<>(), target);
        return resultArr;
    }
}

ArrayList 为引用传参,对其进行修改,会导致其中的值发生变化,因此需要 tarr 作为中间变量处理。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务