Java result with 3 stacks


  • 0
    D

    public List<List<Integer>> pathSum(TreeNode root, int sum1) {
    List<List<Integer>> result = new ArrayList();
    Stack<List<Integer>> list = new Stack();
    Stack<TreeNode> input = new Stack();
    Stack<Integer> sum = new Stack<Integer>();

        if(root!=null)
        {
            input.push(root);
            List<Integer> temp =  new ArrayList();
            temp.add(root.val);
            list.push(temp);
            
            if(root.val==sum1 &&  root.left==null && root.right==null)
            {
                result.add(temp);
                return result;
            }
            sum.push(root.val);
        }
        
        while(!input.isEmpty())
        {
            TreeNode data = input.pop();
            int temp_sum = sum.pop();
            List<Integer> prevlist = list.pop();
            System.out.println(prevlist);
            if(data.left!=null)
            { 
                input.add(data.left);  
                sum.add(temp_sum+data.left.val);
                List<Integer> temp= new ArrayList(prevlist);
                temp.add(data.left.val);
                list.push(temp);
            }
            
            if(data.right!=null)
            {
                input.add(data.right);
                sum.add(temp_sum+data.right.val);
                List<Integer> temp1= prevlist;
                temp1.add(data.right.val);
                list.push(temp1);
            }
            
            if(temp_sum==sum1 &&data.left==null && data.right==null)
                result.add(prevlist);
    
        }
        
        return result;
        
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.