Tuesday, April 30, 2019

Lintcode 246. Binary Tree Path Sum II

Your are given a binary tree in which each node contains a value. Design an algorithm to get all paths which sum to a given value. The path does not need to start or end at the root or a leaf, but it must go in a straight line down.

Example

Example 1:
Input:
{1,2,3,4,#,2}
6
Output:
[
  [2, 4],
  [1, 3, 2]
]
Explanation:
The binary tree is like this:
    1
   / \
  2   3
 /   /
4   2
for target 6, it is obvious 2 + 4 = 6 and 1 + 3 + 2 = 6.
Example 2:
Input:
{1,2,3,4}
10
Output:
[]
Explanation:
The binary tree is like this:
    1
   / \
  2   3
 /   
4   
for target 10, there is no way to reach it.

Code (Java):

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: the root of binary tree
     * @param target: An integer
     * @return: all valid paths
     */
    public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
        // write your code here
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        
        binaryTreePathSum2Helper(root, target, new ArrayList<Integer>(), ans);
        
        return ans;
    }
    
    private void binaryTreePathSum2Helper(TreeNode root, int target, List<Integer> curList, List<List<Integer>> ans) {
        if (root == null) {
            return;
        }
        
        curList.add(root.val);
        int sum = 0;
        for (int i = curList.size() - 1; i >= 0; i--) {
            sum += curList.get(i);
            if (sum == target) {
                List<Integer> temp = new ArrayList<>();
                for (int j = i; j < curList.size(); j++) {
                    temp.add(curList.get(j));
                }
                ans.add(temp);
            }
        }
        
        binaryTreePathSum2Helper(root.left, target, curList, ans);
        binaryTreePathSum2Helper(root.right, target, curList, ans);
        
        curList.remove(curList.size() - 1);
    }
}

1 comment:

  1. hi, which order of questions of lintcode are you working on

    ReplyDelete