每天刷一道牛客题霸-第16天-二叉树根节点到叶子节点和

题目

https://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a?tpId=190&&tqId=35333&rp=1&ru=/ta/job-code-high-rd&qru=/ta/job-code-high-rd/question-ranking

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
     public static ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>();
    public  ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
        // write code here
//         resultList = new ArrayList<ArrayList<Integer>>();
     resultList = new ArrayList<ArrayList<Integer>>();

        if(root == null){
            return resultList;
        }else{
            getPathSum(root,sum,new ArrayList<Integer>());
        }    
        return resultList;
    }
    public  void getPathSum(TreeNode root, int sum, ArrayList<Integer> list){
        if(root == null){
            return;
        }

        sum = sum - root.val;

        if(root.right == null && root.left == null && sum == 0){
            list.add(root.val);
            resultList.add(new ArrayList<Integer>(list));
            list.remove(list.size() - 1);
            return;
        }

         list.add(root.val);
        getPathSum(root.left,sum,list);
        getPathSum(root.right,sum,list);
             list.remove(list.size() - 1);
    }
}
#牛客题霸##题解#
全部评论

相关推荐

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