androidengineers.Book a session

Trees

General Trees and N-ary Trees

article22 minMedium

While binary trees restrict nodes to at most two children, real-world hierarchies — such as file system folder structures, JSON documents, and Android layout view hierarchies — require nodes to support an arbitrary number of children.

These are called General Trees or N-ary Trees.


Representation 1: List of Children

The most direct implementation stores children as an array or list:

class NaryNode<T>(
    val value: T,
    val children: MutableList<NaryNode<T>> = mutableListOf()
)
                   [ Root ]
             /        |        \
        [ Child 1 ] [ Child 2 ] [ Child 3 ]

Trade-offs:

  • Pros: Direct, intuitive access to any k-th child.
  • Cons: Every node allocates a List object, adding pointer memory overhead for leaf nodes that have zero children.

Representation 2: First-Child / Next-Sibling (LCRS Representation)

In memory-constrained systems, an N-ary tree can be represented using only two pointers per node, identical to a binary tree!

  1. firstChild: Points to the node's first direct child.
  2. nextSibling: Points to the next sibling on the same level.
       [ A ]
         | (firstChild)
         v
       [ B ] ----(nextSibling)----> [ C ] ----(nextSibling)----> [ D ]
         | (firstChild)
         v
       [ E ]
class LCRSNode<T>(
    val value: T,
    var firstChild: LCRSNode<T>? = null,
    var nextSibling: LCRSNode<T>? = null
)

Every general tree can be converted into an equivalent binary tree representation using this technique, saving significant memory.


Real-World Case Study: Android View Hierarchy

In Android, every screen is an N-ary tree:

  • ViewGroup extends View and acts as an internal node holding children.
  • TextView, Button, ImageView are leaf nodes.
abstract class View
open class ViewGroup : View() {
    private val children = ArrayList<View>()
    
    fun dispatchDraw(canvas: Canvas) {
        for (child in children) {
            child.draw(canvas) // N-ary Pre-Order Tree Traversal!
        }
    }
}

During rendering, the Android framework traverses this tree to perform:

  1. Measure Pass: Bottom-up traversal (Post-Order) to determine sizes.
  2. Layout Pass: Top-down traversal (Pre-Order) to position elements on screen.
  3. Draw Pass: Paints components sequentially onto the GPU framebuffer.

Summary

  • N-ary Trees allow any number of child nodes per parent.
  • Can be represented as a List of Children or via the memory-efficient Left-Child Right-Sibling (LCRS) binary pointer pair.
  • Android layout hierarchies and DOM structures are N-ary trees.

YOUR LEARNING JOURNEY

0 of 55 available lessons completed

Progress saved in this browser. No account needed.
General Trees and N-ary Trees | Data Structures | Android Engineers