Labs ICT
Pro Login

Tree Basics

Nodes, edges, and the hierarchy of data.

What Are Trees?

Trees are everywhere in programming, and once you see them, you can't unsee them. A tree is a way to organize data in a hierarchy — think family trees, company org charts, or folders on your computer.

The top of the tree is called the root. Every other item is a node connected by edges. Nodes can have children, and nodes with no children are called leaves. It's exactly like a real tree, just upside down.

Trees are great because they let you represent relationships naturally. Not everything is a flat list — some data is inherently nested, and trees handle that perfectly.

Key Terms You Need to Know

The root node is the starting point — it has no parent. Every other node has exactly one parent. A node's children are the nodes directly below it. The path from the root to any node is unique, which is what makes trees so useful for searching.

A leaf node has no children. The height of a tree is the longest path from root to leaf. The depth of a node is how far it is from the root. These concepts show up everywhere in tree algorithms.

Here's a fun fact: your browser's DOM is a tree. The HTML element is the root, and everything else — head, body, divs, paragraphs — are nodes in that tree. CSS is basically a set of rules for styling tree nodes.

class TreeNode {
  constructor(value) {
    this.value = value;
    this.children = [];
  }

  addChild(value) {
    const child = new TreeNode(value);
    this.children.push(child);
    return child;
  }
}

const root = new TreeNode("CEO");
const vp1 = root.addChild("VP Engineering");
const vp2 = root.addChild("VP Sales");
vp1.addChild("Dev Lead");
vp1.addChild("QA Lead");
Try it Yourself →

Real-World Examples

Your file system is a tree. The C: drive (or /) is the root, folders are internal nodes, and files are leaves. Every file has exactly one parent folder, and you navigate the tree by going deeper into folders.

The DOM is another tree. The document object is the root, and every HTML element is a node. When you call document.querySelector(), you're searching this tree for a specific node.

Even organizational charts are trees — the CEO at the top, managers in the middle, and individual contributors at the leaves. Trees model any situation where things have a one-to-many parent-child relationship.