leetode -- 113. Path Sum II

題目描述

題目難度: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.
在這裏插入圖片描述

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);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章