[Leetcode]113. Path Sum II 求路径和一个数的所有路径

来源:互联网 发布:mac系统用windows软件 编辑:程序博客网 时间:2024/05/01 11:29

题目:

题意:给定一个二叉树,和一个整数,求二叉树中所有从根节点到叶子节点的路径和等于这个整数的路径。

代码实现:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    List<List<Integer>> result = new ArrayList<>();    public List<List<Integer>> pathSum(TreeNode root, int sum) {        if(root == null){            return result;        }        ArrayList<Integer> list = new ArrayList<>();        myPathSum(root, sum, 0, list);        return result;    }    public void myPathSum(TreeNode root, int sum, int current_sum, ArrayList<Integer> list) {        list.add(root.val);        current_sum += root.val;        if (current_sum == sum && root.left == null && root.right == null) {            result.add(new ArrayList<>(list));            return;        }        if (root.left != null) {            myPathSum(root.left, sum, current_sum, new ArrayList<>(list));        }        if (root.right != null) {            myPathSum(root.right, sum, current_sum, new ArrayList<>(list));        }    }}

代码中要注意的问题:1.左右子树递归的时候 要使用 new ArrayList<>(list) 而不是使用list, 使用list最后会多加结点

0 0