Tree
In one line
A tree is a hierarchical data structure where each node has one parent and zero or more children, starting from a root.
In simple words
A tree is a hierarchical structure made of nodes. There is one root node at the top, and every other node has exactly one parent and zero or more children. Nodes with no children are leaves. This parent-child relationship creates a branching structure that resembles an upside-down tree.
Trees are everywhere in computing: the file system (folders and files), the DOM (HTML elements), abstract syntax trees (parsed code), decision trees, and search trees. The most common variant is the binary tree (each node has at most two children), and specifically the binary search tree where left children are smaller and right children are larger — enabling O(log n) search.
Tree operations include traversal (visiting every node in pre-order, in-order, or post-order), search, insertion, and deletion. Trees are the natural structure for representing hierarchical data and for algorithms that divide problems into sub-problems.
Example
class TreeNode {
constructor(value) { this.value = value; this.children = []; }
}
const root = new TreeNode("root");
const a = new TreeNode("a"); const b = new TreeNode("b");
root.children.push(a, b);
a.children.push(new TreeNode("a1"));
function traverse(node, depth = 0) {
console.log(" ".repeat(depth) + node.value);
node.children.forEach(c => traverse(c, depth + 1));
}
traverse(root);
// root
// a
// a1
// bEach TreeNode holds a value and a list of children. traverse() recursively visits every node in depth-first order.
Related terms
Related Resources
Related Lessons
- Data Structures
Learn trees and graphs.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.