How to modify my code to be correct (iteration using Stack, Java)?


  • 0

    I think my code is just close to be right. My result of the test case below is [[5,4,11,2],[5,4,11,8,4,5]]. And the correct result is [[5,4,11,2],[5,8,4,5]].

    [5,4,8,11,null,13,4,7,2,null,null,5,1]
    22
    

    Obviously I didn't delete those values after I got a correct list. But I don't know how to delete those values. Any suggestions will be appreciated. Here is my code:

    public List<List<Integer>> pathSum(TreeNode root, int sum)
        {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (root == null) return res;
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            
            Stack<Integer> val = new Stack<Integer>();
            val.push(root.val);
            List<Integer> list = new ArrayList<Integer>();
            while (!stack.empty() && stack.peek() != null) {
                TreeNode node = stack.pop();
                int tmpVal = val.pop();
                list.add(node.val);
                if (node.left == null && node.right == null) {
                    if (tmpVal != sum)
                        list.remove(list.size() - 1);
                    else {
                        res.add(new ArrayList<>(list));
                        // while (list.size() != 1) {
                            list.remove(list.size() - 1);
                        // }
                    }
                }
                if ((node.left == null && node.right == null) || )
                
                if (node.right != null) {
                    stack.push(node.right);
                    val.push(node.right.val + tmpVal);
                }
                if (node.left != null) {
                    stack.push(node.left);
                    val.push(node.left.val + tmpVal);
                }
            }
            return res;
        }
    

Log in to reply
 

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