Tree
ELI5 — The Vibe Check
A tree is a data structure shaped like an upside-down tree — one root at the top, branches going down, and leaves at the very bottom. Each item (node) can have children. The DOM in your browser is a tree. File systems are trees. Family trees are trees. They are great for hierarchical data.
Real Talk
A tree is a hierarchical data structure consisting of nodes connected by edges, with one root node at the top and child nodes branching below. Trees are acyclic (no loops). Important tree types include binary trees (max 2 children), binary search trees (BST, ordered for O(log n) search), AVL/red-black trees (self-balancing), tries (prefix trees), and heaps. The DOM, file systems, and ASTs are all tree structures.
Show Me The Code
// Binary Search Tree node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// BST property: left < node < right
// 8
// / \
// 3 10
// / \ \
// 1 6 14
// Search is O(log n) in a balanced tree
When You'll Hear This
"The file system is a tree — use recursion to traverse it." / "A BST gives you O(log n) search if it stays balanced."
Related Terms
Data Structure
A data structure is a way of organizing information in your code so it is easy to use and fast to access.
DOM (Document Object Model)
The DOM is a live map of your webpage that JavaScript can read and edit. When the browser loads your HTML it turns it into a big tree of objects.
Graph
A graph is like a network of dots connected by lines. Each dot is a node and each line is an edge.
Recursion
Recursion is when a function calls itself to solve a smaller version of the same problem, like a set of Russian nesting dolls.