Lesson 17 of 30
Trees explained through the family tree you already know how to read: one ancestor at the top, branching down into children, and their children after that.
10 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
This topic is about judgment and practical tradeoffs more than a single right answer — a mock interview is the better way to test yourself on it.
Be interviewed on this →Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
You've probably seen a family tree before — maybe drawn on a poster board, maybe sketched on paper. One person sits at the top. Lines drop down from them to their children. Lines drop down from each of those children to their own children. The whole shape branches downward, wider at the bottom than at the top.
A tree, in code, is exactly that shape, holding any kind of data instead of family members. One item sits at the top. It connects downward to a few items below it. Each of those connects downward to a few more. Nothing loops back up — everything flows in one direction, top to bottom, just like a family tree never has your grandchild also be your grandparent.
Because you already know how to read a family tree, you already know most of the vocabulary trees use in code. It's worth learning these words on purpose, because they show up constantly once you start reading about trees:
// Each person is a node: a name, and a list of their children (also nodes).
function makePerson(name, children = []) {
return { name, children };
}
// Build from the bottom up, then attach children to their parent.
const grandchild1 = makePerson("Mia");
const grandchild2 = makePerson("Leo");
const child = makePerson("Sam", [grandchild1, grandchild2]); // Sam is the parent here
const root = makePerson("Ana", [child]); // Ana is the root — nobody above her
// Print the whole family, indenting each generation to show depth.
function printFamily(person, depth = 0) {
console.log(" ".repeat(depth) + person.name);
for (const kid of person.children) {
printFamily(kid, depth + 1); // walk down into each child
}
}
printFamily(root);
// Ana
// Sam
// Mia
// Leo
Mia and Leo are leaves here — the code never finds any children for them, because their children array is empty by default.
Family trees already showed you the words "root," "parent," and "child" long before any code did. Everything you learn about trees from here — including the special two-children-max version coming up next — is this exact same branching shape, with one extra rule layered on top.