> しかし、それ以外のパターンのアルゴリズムがわからず。。。
行頭 → <ul> * $depth[n]
$depth[n-1]-$depth[n]=1 → <ul>
$depth[n-1]-$depth[n]=2 → <ul><ul>
$depth[n-1]-$depth[n]=-1 → </ul>
行末 → </ul> * $depth[n]

単純にこれじゃダメかい?