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

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

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 {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param target int整型
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> FindPath (TreeNode root, int target) {
        // write code here
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        if(root==null){
            return list;
        }
        ArrayList<Integer> songList = new ArrayList<>();
        int sum = 0;
        FindPath1(root, target, sum, list, songList);
        return list;
    }
    public void FindPath1(TreeNode root, int target, int sum,
                          ArrayList<ArrayList<Integer>> list, ArrayList<Integer> sonList) {
        sum += root.val;
        sonList.add(root.val);
        if (root.left == null && root.right == null) {
            if (sum == target) {
                ArrayList<Integer> list1 = new ArrayList<>();
                list1.addAll(sonList);
                list.add(list1);
            }
        }
        if (root.left != null) {
            FindPath1(root.left, target, sum, list, sonList);
        }
        if (root.right != null) {
            FindPath1(root.right, target, sum, list, sonList);
        }
        sonList.remove(sonList.size() - 1);
    }

}

全部评论

相关推荐

后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务