@@ -479,9 +479,56 @@ func (n *Node) Unsplit() bool {
479479 if n .parent .IsLeaf () {
480480 return n .parent .Unsplit ()
481481 }
482+
483+ n .parent .flatten ()
482484 return true
483485}
484486
487+ // flattens the tree by removing unnecessary intermediate parents that have only one child
488+ // and handles the side effect of it
489+ func (n * Node ) flatten () {
490+ if n .parent == nil {
491+ return
492+ }
493+
494+ ind := 0
495+ for i , c := range n .parent .children {
496+ if c .id == n .id {
497+ ind = i
498+ }
499+ }
500+
501+ if len (n .children ) == 1 {
502+ // Replace current node with child node to remove chained parent
503+ n .parent .children [ind ] = n .children [0 ]
504+ n .parent .children [ind ].parent = n .parent
505+ n .parent .children [ind ].Kind = n .Kind
506+
507+ // Flatten the child node that replaced the current node
508+ n .parent .children [ind ].flatten ()
509+ } else if ! n .IsLeaf () && n .Kind == n .children [0 ].Kind {
510+ // If we have the same kind as the children (cuased by previous flattening),
511+ // replace this node with our children.
512+ origsize := len (n .parent .children )
513+
514+ // Let's say we have 5 children and want to replace [2] with its children [a] [b] [c]
515+ // [0] [1] [2] [3] [4] --> [0] [1] [a] [b] [c] [3] [4]
516+ // insertcount will be `3 - 1 = 2` in this case
517+ insertcount := len (n .children ) - 1
518+ n .parent .children = append (n .parent .children , make ([]* Node , insertcount )... )
519+ if ind != insertcount - 1 {
520+ copy (n .parent .children [(ind + insertcount + 1 ):], n .children [(ind + 1 ):origsize ])
521+ }
522+ for i := 0 ; i < len (n .children ); i ++ {
523+ n .parent .children [ind + i ] = n .children [i ]
524+ n .parent .children [ind ].parent = n .parent
525+ }
526+ }
527+
528+ // Update propW and propH since the parent of the children might have been updated
529+ n .parent .markSizes ()
530+ }
531+
485532// String returns the string form of the node and all children (used for debugging)
486533func (n * Node ) String () string {
487534 var strf func (n * Node , ident int ) string
0 commit comments