What is a tree as a data structure?
A tree is a hierarchical data structure in which every element (called a node) can have child nodes, but only one parent (except the root).
Key concepts
- Root - the top node, which has no parent.
- Children - nodes that branch out from a parent.
- Leaves - nodes with no children.
- Edge - the connection between a parent and a child.
- Tree height - the length of the longest path from the root to a leaf.
The core idea
A tree stores data as a hierarchy, not in a linear order (like a list or a queue).
Example
javascript
A ← root
/ \
B C ← children of A
/ \
D E ← leavesCommon types of trees
- Binary tree - each node has at most two children.
- Search tree (BST) - left child < parent < right child.
- Prefix tree (Trie) - used to store strings and support autocomplete.
- AVL, red-black tree - balanced variants that speed up search.
Summary
A tree is a structure where data is organized by levels, which makes search, sorting, hierarchical storage, and traversal efficient.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.