首页 > 每天刷一道牛客题霸-第16天-二叉树根节点到叶子节点和
头像
菜鸟也要飞的高
编辑于 2020-12-22 10:18
+ 关注

每天刷一道牛客题霸-第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);
    }
}

全部评论

(0) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期热帖

近期精华帖

热门推荐