def __leaf(i, j, first, maxfirst, prevleaf, ancestor):
    """
    Determine if j is leaf of i'th row subtree.
    """
    jleaf = 0
    if i <= j or first[j] <= maxfirst[i]:
        return -1, jleaf
    maxfirst[i] = first[j]
    jprev = prevleaf[i]
    prevleaf[i] = j
    if jprev == -1:
        jleaf = 1
    else:
        jleaf = 2
    if jleaf == 1:
        return i, jleaf
    q = jprev
    while q != ancestor[q]:
        q = ancestor[q]
    s = jprev
    while s != q:
        sparent = ancestor[s]
        ancestor[s] = q
        s = sparent
    return q, jleaf
