Fork me on github

113 路径之和II

回溯,全局变量

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<List<Integer>> res  = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root == null){
            return res;
        }

        helper(root, sum, new ArrayList<>());
        return res;
    }

    public void helper(TreeNode root, int sum, List<Integer> cur){
        if(root.left == null && root.right == null){
            if(sum == root.val){
                cur.add(root.val);
                res.add(new ArrayList<>(cur));
                cur.remove(cur.size() - 1);
            }
        }
        else{
            cur.add(root.val);
            if(root.left != null){
                helper(root.left, sum - root.val, cur);
            }
            if(root.right != null){
                helper(root.right, sum - root.val, cur);
            }
        cur.remove(cur.size() - 1);

        }
    }
}
posted @ 2020-08-26 23:04  zjy4fun  阅读(104)  评论(0编辑  收藏  举报