Trees & the View Hierarchy
What is a tree?
A tree is a structure of nodes where each node has children, starting from a single root, with no cycles. It models anything hierarchical — and as a mobile developer you stare at a tree all day: your view/widget hierarchy is a tree, the root being the screen and the leaves being individual buttons and text.
Why this matters for performance
When your screen renders, the system traverses this tree to measure and lay out every node. A deep or bloated hierarchy means more traversal work each frame — a real cause of jank. This is why flat layouts (ConstraintLayout on Android, or fewer nested widgets in Flutter/Compose) perform better: a shallower tree is faster to walk.
Traversing a tree
Two fundamental ways to visit every node:
- Depth-First (DFS) — go deep down one branch before backtracking. Uses recursion or a stack. Good for “process this node and all its descendants”.
- Breadth-First (BFS) — visit level by level. Uses a queue. Good for “find the nearest matching node”.
// DFS with recursion
fun dfs(node: Node) {
visit(node)
for (child in node.children) dfs(child)
}
// BFS with a queue
fun bfs(root: Node) {
val queue = ArrayDeque<Node>()
queue.add(root)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
visit(node)
queue.addAll(node.children)
}
}
Other trees you’ll meet
- File system — folders and files (recursive size calculations).
- Nested JSON from an API — objects within objects.
- Binary Search Tree (BST) — a sorted tree giving O(log n) search/insert (the idea behind many ordered collections).
- Trie — a tree of characters powering fast autocomplete/search-as-you-type.
Binary search trees, briefly
A BST keeps smaller values left and larger right, so searching halves the space each step — O(log n) when balanced. Most languages’ sorted maps/sets are balanced trees under the hood, giving you ordered data with fast operations.
Common mistakes
- Deeply nested view hierarchies that slow down layout — flatten them.
- Using DFS recursion on very deep trees (stack overflow) — use an explicit stack/BFS.
- Re-traversing the whole tree when you could cache or diff.
Summary: Trees model hierarchies — including your view hierarchy, which the system traverses every frame, so keep it shallow. Learn DFS (stack/recursion) and BFS (queue) to walk trees, and know BSTs/tries power fast ordered search and autocomplete.