Path Sum II

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] ]

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
 public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<>();
        pathSum(root, sum, 0, new ArrayList<Integer>(), result);
        return result;
    }

    public void pathSum(TreeNode root, int sum, int cur, List<Integer> list, List<List<Integer>> result) {
        if (root == null) return;

        cur += root.val;
        list.add(root.val);
        if (root.left == null && root.right == null) {
            if (cur == sum) {
                result.add(new ArrayList<>(list));
            }

            return;
        }

        if (root.left != null) {
            pathSum(root.left, sum, cur, list, result);
            list.remove(list.size() - 1);
        }

        if (root.right != null) {
            pathSum(root.right, sum, cur, list, result);
            list.remove(list.size() - 1);
        }

    }
}

results matching ""

    No results matching ""