Skip to content

Tree Basics

Lesson 1 of 14 · 4 min

Tree Basics

Step 1 of 6

One node sits at the top with nothing above it. That is the root.

The Idea

A tree stores values in nodes that fan out downward. One node is the root; every other node has exactly one parent, and nodes with no children are leaves. Links only point down, so a tree has no cycles and no way back up.

Real-World Example

Nested folders on a disk. One folder sits at the top, every folder below it lives inside exactly one parent, and files are the dead ends. How deep something is buried is simply how many folders you had to open to reach it.

The Code

Your turn

What does this print?

class Node:
  def __init__(self, v, kids=None): self.val, self.kids = v, kids or []

t = Node(1, [Node(2), Node(3, [Node(4)])])
print(len(t.kids), t.kids[1].kids[0].val)

Mini quiz

1 / 3

How many parents does a non-root node have?