LeetCode 113. Path Sum II(java)

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1 ```
return
[
   [5,4,11,2],
   [5,8,4,5]
] 
recursion解法,树的解法比较固定,分为base case和recursion rule,然后定好参数,在需要的时候调用自身即可。
public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        helper(res, root, new ArrayList<Integer>(), sum);
        return res;
    }
    public void helper(List<List<Integer>> res, TreeNode root, ArrayList<Integer> path, int sum) {
        //base case: leaf
        if (root.left == null && root.right == null) {
            if (root.val == sum) {
                path.add(root.val);
                res.add(new ArrayList<Integer>(path));
                path.remove(path.size() - 1);
            }
            return;
        }
        //recursion rule: non-leaf
        path.add(root.val);
        if (root.left != null) helper(res, root.left, path, sum - root.val);
        if (root.right != null) helper(res, root.right, path, sum - root.val);
        path.remove(path.size() - 1);
        return;
    }
阅读更多
文章标签: java leetcode
个人分类: Tree
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭