This code seems to pass in eclipse editor but fails testcase is {0,1}.


  • 0
    A

    public class Solution {
    private static int sumA = 0;
    private void sumNum(TreeNode root, int val) {
    if (root == null) {
    return ;
    }
    val = val*10 + root.val;

    	if ((root.left == null) && (root.right == null)) {
    		sumA += val;
    	} else {
    		sumNum(root.right,val) ;
    		sumNum(root.left,val);  
    	}
    }
    public int sumNumbers(TreeNode root) {
        sumNum(root,0);
        int ret = sumA;
        return ret;
    }
    

    }


  • 0
    M

    Global and static variables persist between runs, so sumA will need to be reset between runs, or you'll get wrong answers in future inputs. In other words,

    public int sumNumbers(TreeNode root) {
        sumA=0;
        sumNum(root,0);
        int ret = sumA;
        return ret;
    }
    

    Please see "Why does my code produce a different output compared to my local environment?"


Log in to reply
 

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