Created
November 9, 2019 05:28
-
-
Save chaudharisuresh997/7d92e0ff72cc280d5a84946744dca523 to your computer and use it in GitHub Desktop.
recursion with stack vs array example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { | |
* val = x; | |
* left=null; | |
* right=null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
// ArrayList<Integer> arr=new ArrayList<Integer>(); | |
// ArrayList<ArrayList<Integer>> returnList=new ArrayList<ArrayList<Integer>>(); | |
// public ArrayList<ArrayList<Integer>> pathSum(TreeNode A, int B) { | |
// calc(A,B,arr,returnList,0); | |
// return returnList; | |
// } | |
// public void calc(TreeNode A,int B,ArrayList<Integer> arr,ArrayList<ArrayList<Integer>> returnList,int j){ | |
// if(A==null) | |
// return; | |
// arr.add(A.val); | |
// if(A.left == null && A.right == null) { | |
// if(B==0){//adding result to list | |
// int idx=0; | |
// // System.out.println("START"); | |
// //System.out.println(">"+num); | |
// returnList.add(new ArrayList<Integer>(arr)); | |
// } | |
// } | |
// calc(A.left,B-A.val,arr,returnList,j); | |
// calc(A.right,B-A.val,arr,returnList,j); | |
// arr.remove(arr.size()-1); | |
// // System.out.println("START"); | |
// //arr.forEach(x->System.out.println(x)); | |
// //System.out.println("END"); | |
// } | |
//THIS SOLUTION is from https://github.com/varunu28/InterviewBit-Java-Solutions/blob/master/Trees/Problems/Roots%20To%20Leaf%20Path%20Sum.java | |
private ArrayList<ArrayList<Integer>> resultList = new ArrayList<>(); | |
public void pathSumInner(TreeNode root, int sum, Stack<Integer>path) { | |
path.push(root.val); | |
if(root.left == null && root.right == null) { | |
if(sum == root.val) resultList.add(new ArrayList<Integer>(path)); | |
} | |
if(root.left!=null) pathSumInner(root.left, sum-root.val, path); | |
if(root.right!=null)pathSumInner(root.right, sum-root.val, path); | |
path.pop(); | |
// System.out.println("START"); | |
// path.stream().forEach(x->System.out.println(x)); | |
// System.out.println("END"); | |
} | |
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { | |
if(root==null) return resultList; | |
Stack<Integer> path = new Stack<Integer>(); | |
pathSumInner(root, sum, path); | |
return resultList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment