public static int[] getDimensions(BinaryArray array, int numDimensions) {
    Preconditions.checkArgument(numDimensions >= 1);
    if (array == null) {
      return null;
    }

    // use deep-first search to search to numDimensions-1 layer to get dimensions.
    int depth = 0;
    int[] dimensions = new int[numDimensions];
    int[] startFromLefts = new int[numDimensions];
    BinaryArray[] arrs = new BinaryArray[numDimensions]; // root to current node
    BinaryArray arr = array;
    while (depth < numDimensions) {
      arrs[depth] = arr;
      int numElements = arr.numElements();
      dimensions[depth] = numElements;
      if (depth == numDimensions - 1) {
        break;
      }
      boolean allNull = true;
      if (startFromLefts[depth] == numElements) {
        // this node's subtree has all be traversed, but no node has depth count to numDimensions-1.
        startFromLefts[depth] = 0;
        depth--;
        continue;
      }
      for (int i = startFromLefts[depth]; i < numElements; i++) {
        if (!arr.isNullAt(i)) {
          arr = arr.getArray(i);
          allNull = false;
          break;
        }
      }
      if (allNull) {
        // startFromLefts[depth-1] = 0;
        depth--; // move up to parent node
        startFromLefts[depth]++;
        arr = arrs[depth];
      } else {
        depth++;
      }
      if (depth <= 0) {
        return null;
      }
    }

    return dimensions;
  }
@Test
  public void getDimensionsTest() {
    {
      int[] arr = new int[] {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2};
      int[] dimensions = BinaryArray.getDimensions(BinaryArray.fromPrimitiveArray(arr), 1);
      Assert.assertEquals(dimensions, new int[] {arr.length});
    }

    {
      BinaryArrayWriter writer =
          new BinaryArrayWriter(DataTypes.arrayField(DataTypes.PRIMITIVE_INT_ARRAY_FIELD));
      writer.reset(4);
      int[] a = new int[] {1, 2, 1};
      writer.setNullAt(0);
      writer.setNullAt(1);
      writer.write(2, BinaryArray.fromPrimitiveArray(a));
      writer.write(3, BinaryArray.fromPrimitiveArray(a));
      BinaryArray array = writer.toArray();

      int[] dimensions = BinaryArray.getDimensions(array, 2);
      Assert.assertEquals(dimensions, new int[] {4, 3});
    }
  }