Java Question. Why the global variable can't be static?

  • 0
    public class Solution {
    // Global variable to tack path
    // I normally declare it as static
    // for whatever reason, it give me wrong answer
    // Could somebody explain why? Thanks.
    List<String> list = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        help(root, "");
        return list;
    private void help(TreeNode root, String s) {
        if(root == null) return;
        s += root.val;
        if(root.left == null && root.right == null) {
        s += "->";
        help(root.left, s);
        help(root.right, s);


    enter code here

  • -2

    if list is static and will be used in the function, your function should be static.

  • 2

    static variable belong to the class, and reinitialized during class loading. Since the test suite probably not reloading the Solution class every time it execute new test, the static variable from previous test will likely not empty.

Log in to reply

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