1. 程式人生 > >LeetCode 113. Path Sum II(java)

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; }