VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 10: Trees and BSTs

Lesson 10.1 of 14 in this module Unrolled Pro

Trees, Traversals and Recursive Thinking

A tree is data where each item has children, and almost every tree algorithm is 'solve the subtrees, then combine at the root'. From recomputing each subtree's size from scratch (O(n²)), to one post-order pass that returns sizes upward (O(n)). Then the four traversal orders (pre, in, post, level) and what each is for, iterative versions with an explicit stack for deep trees, the O(h) space that recursion really costs, and walking a model's module tree or a nested config the same way.

about 10 min 5 Python examples 1 quick checks

The question this module answers: how do you compute something over data shaped like a hierarchy? A binary tree is a node with a value and up to two children, each the root of a smaller tree. That self-similarity is the whole trick: if you can answer the question for the left subtree and for the right subtree, you can usually answer it for the whole tree with one small step at the root.

ML context.

  • Decision trees and ensembles: every prediction is a walk from the root to a leaf (lesson 10.14); gradient-boosted models are hundreds of such trees.
  • Model structure: a PyTorch model is a tree of modules; named_modules(), parameter counting and freezing layers are tree traversals.
  • Nested data: JSON configs, parse trees of code and text, hierarchical labels (animal → dog → terrier), file trees of a dataset.
  • Index structures: binary search trees, B-trees in databases, k-d trees for nearest neighbours (lesson 9.10).

1. The problem: a value for every subtree

Task: for every node, compute the size of its subtree (the number of nodes in it, itself included). Think of counting parameters per module in a model.

The direct approach counts each subtree from scratch:

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Trees, Traversals and Recursive Thinking"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee