Can anyone help me to find the mistake?


  • 0
    J

    I have a Wrong Answer on the case:
    Input: {1,-2,-3,1,3,-2,#,-1}, 2

    Output: false

    Expected: true

    public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)  return false;
        
        Stack<TreeNode> stack = new Stack<>();
        HashSet<TreeNode> visitedSet = new HashSet<>();
        stack.push(root);
        visitedSet.add(root);
        TreeNode tmp = new TreeNode(0);
        int result = 0;
        
        while(!stack.isEmpty())
        {
            tmp = stack.peek().left;       //dfs
            if(tmp!=null && !visitedSet.contains(tmp)){
                stack.push(tmp);
                visitedSet.add(tmp);
                continue;
            }
            tmp = stack.peek().right;     //dfs
            if(tmp!=null && !visitedSet.contains(tmp)){
                stack.push(tmp);
                visitedSet.add(tmp);
                continue;
            }
            
            if(stack.peek().left==null && stack.peek().right==null){      //check weather is leaf node
                result = calculate(stack);
                if(result==sum){
                    return true;
                }
            }
            else{
                stack.pop();
            }
        }
        return false;
    }
    
    private int calculate(Stack<TreeNode> stack){
        int sum = 0;
        TreeNode tmp = new TreeNode(0);
        while(!stack.isEmpty()){
            tmp = stack.pop();
            sum += tmp.val;
        }
        return sum;
    }
    

    }


Log in to reply
 

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