Friday, September 18, 2015

Tree - Sum Paths

Problem

Given a binary tree, not necessarily a BST return all paths with sum x:
Example for sum =5 and tree given below:

         1
        /   \
           2     3
         / \          / \
      2  -1      0   8
      /\   /\       /\     /\
   0  3 -5 4   6 -9 -6 1

Output is: [[1,2,2],[2,3],[1,2,2,0],[2,-1,4],[3,8,-6]]

Solution

public class Tree{
	int val;
	Tree left;
	Tree right;
} 

package Tree;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class TreeSumPath {

	Set< ArrayList<Integer> > sumPaths2;
	
	void doTraversal(Tree t, int remain, int oSum, ArrayList temp){
		temp.add(t.val);
		if(remain == 0) sumPaths2.add(temp);
		traverse2(t.left, remain, temp, oSum);
		traverse2(t.right, remain, temp, oSum);
	}
	
	void traverse2(Tree t, int sum, ArrayList curNodes, int oSum){
		if(t==null) return;
		ArrayList temp = new ArrayList(curNodes);
		doTraversal(t, sum - t.val, oSum, temp);
		
		temp = new ArrayList();
		doTraversal(t, oSum-t.val, oSum, temp);
	}

	Set< ArrayList<Integer> > getSumPaths(Tree t, int sum){
		sumPaths2 = new HashSet< ArrayList>();
		traverse2(t, sum, new ArrayList(), sum);
		System.out.println(sumPaths2);
		return sumPaths2;
	}
	
	public static void main(String[] args) {
		Tree t = TreeTestData.getSampleTree3();
		TreeSumPath ob = new TreeSumPath();
		ob.getSumPaths(t, 5);
	}
}

No comments:

Post a Comment