This entire method is pretty complex for what it does.  I think if you rebase this onto current master you can take advantage of the changes I made to AbstractTreeIterator recently:

  
  private static int nextSlash(byte[] pathBuf, int ptr, int end) {
    while (ptr < end && pathBuf[ptr] != '/')
      ptr++;
    return ptr;
  }

  public static TreeWalk forPath(final ObjectReader reader, final String path,
			final AnyObjectId... trees) throws MissingObjectException,
			IncorrectObjectTypeException, CorruptObjectException, IOException {
    byte[] pathBuf = Constants.encode(path);

    TreeWalk tw = new TreeWalk(reader);
    tw.reset(trees);

    int ptr = 0;
    int end = nextSlash(pathBuf, ptr, pathBuf.length);
    int mode = end < path.length
      ? FileMode.TREE.getBits()
      : -1;

    while (tw.next()) {
      int cmp = tw.currentHead.pathCompare(pathBuf, ptr, end, mode);
      if (cmp < 0)
        continue;
      if (cmp > 0)
        return null;
      if (end == path.length)
        return tw;

      ptr = end + 1;
      end = nextSlash(pathBuf, ptr, pathBuf.length);
      mode =  mode = end < pathBuf.length
        ? FileMode.TREE.getBits()
        : -1; 
      tw.enterSubtree();
    }

    return null;
  }

And you'll need to make a tiny change to AbstractTreeIterator.pathCompare.  On line 353 before the mode of both entries is considered insert:

    if (bMode == -1)
      return 0;
    return lastPathChar(mode) - lastPathChar(bMode);

Basically lets fix forPath() instead of adding a new special method.