Trees: Hierarchical Data
Learn about trees, the non-linear data structures that are fundamental to file systems, databases, and especially the **Document Object Model (DOM)** that structures every web page.
What Is a Tree?
A tree is a hierarchical data structure consisting of nodes connected by edges. Unlike arrays or linked lists, which are linear, trees are non-linear. The topmost node is called the **root**. Each node can have zero or more child nodes. A node with no children is a **leaf**.
Think of a family tree or a company's organizational chart. In frontend development, the most important tree is the DOM, where the <html> tag is the root and every other element is a node. This structure is what allows JavaScript to efficiently find and manipulate page elements.
Binary Search Trees (BSTs)
A **Binary Search Tree** is a special type of tree with important properties that make searching for data incredibly efficient:
- Each node has at most two children (a left child and a right child).
- For any given node, all values in its **left subtree** are less than the node's value.
- For any given node, all values in its **right subtree** are greater than the node's value.
This ordering means we can find any value in the tree with an average time complexity of **O(log n)**, which is significantly faster than the O(n) required to search an unsorted array.