Skip to content
BytePatterns

Tree Basics

Trees & BST: lesson 1 of 14

One root, many branches, and no way back up.

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

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

root = Node("home", [Node("docs", [Node("cv.pdf")]), Node("photos")])

def height(node):                      # longest link count below this node
    return 0 if not node.kids else 1 + max(height(k) for k in node.kids)

print(root.val)                        # home  -> the root
print([k.val for k in root.kids])      # ['docs', 'photos']
print(root.kids[1].kids == [])         # True  -> photos is a leaf
print(height(root))                    # 2     -> edges to the deepest file

Python

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?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.