O(1) space with twice in-order list. but error occurs, can anyone tell me why?

• reference to https://discuss.leetcode.com/topic/77335/proper-o-1-space, I write it myself, but I got an error:

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {

private static int count = 0;
private static int maxCount = 0;
private static int modeCount = 0; // the size of modes
private static int modes[];
private static Integer val = null;
private static int idx = 0;
public int[] findMode(TreeNode root) {
inorderCount(root); // get modeCount
modes = new int[modeCount];
val = null;
count = 0;
inorderModes(root);
return modes;
}

// in-order list to get modeCount and maxCount
private static void inorderCount(TreeNode root) {
if (root == null) return;
inorderCount(root.left);
count = (val != null && root.val == val)?count+1:1;
if (count > maxCount) {
modeCount = 1;
maxCount = count;
} else if (count == maxCount) {
modeCount++;
}
val = root.val;
inorderCount(root.right);
}

// in-order list to compute modes
private static void inorderModes(TreeNode root) {
if (root == null) return;
inorderModes(root.left);
count = (val != null && root.val == val)?count+1:1;
val = root.val;
if (count == maxCount) modes[idx++] = root.val;
inorderModes(root.right);
}

}
``````

in case:

``````Last executed input: [-2,-2,-2]
``````

and get following error:

``````Runtime Error Message: Line 48: java.lang.ArrayIndexOutOfBoundsException: 5
``````

On my computer, no errer occurs. My Java-env is JDK8.

• Because modes[] array is a public variable. Make sure its reset for each input.

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