题目描述

题目难度:Medium
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.
leetode -- 113. Path Sum II

AC代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> resList = new ArrayList<>();
        if(root == null) return resList;
        helper(root, sum, 0, resList, new ArrayList<Integer>());
        return resList;
    }
    
    private void helper(TreeNode root, int sum, int cur, List<List<Integer>> resList, List<Integer> list){
        if(root == null) return;
        if(root.left == null && root.right == null){
            if(cur + root.val == sum){
            list.add(root.val);
            resList.add(new ArrayList(list));
            list.remove(list.size() - 1);
            return;
            }
        }
        list.add(root.val);
        helper(root.left, sum, cur + root.val, resList, list);
        helper(root.right, sum, cur + root.val, resList, list);
        list.remove(list.size() - 1);
}
}

相关文章:

  • 2021-10-05
  • 2021-06-29
  • 2021-09-23
  • 2021-06-30
  • 2022-12-23
  • 2022-12-23
  • 2022-02-25
  • 2021-06-05
猜你喜欢
  • 2021-07-06
  • 2021-07-28
  • 2021-06-14
相关资源
相似解决方案