# Tree

> The Tree data structure is a hierarchical model for representing parent-child relationships, used in organizing data hierarchically.

## What is a tree data structure and how is it different from a graph?

The hierarchical structure where every node except the root has exactly one parent and zero or more child nodes. Commonly used for representing nested data relationships.

- Topic: Basics
- Type: data structure

## Example

Wrong:

```js
function depth(node) {
  return 1 + Math.max(depth(node.left), depth(node.right));
}
```

Right:

```js
function depth(node) {
  if (node === null) return 0;
  return 1 + Math.max(depth(node.left), depth(node.right));
}
```

Without the base case the function reads `left` of `null` and throws a 'TypeError'.

## Common mistakes

- Assuming a binary search tree stays O(log n) when the inserted data is sorted.
- Recursing into children without a `null` check.

## Key points

- Recursive traversal returns at a `null` node before reading its children.
- Binary search tree cost is stated as O(h), which is O(n) when the tree is unbalanced.
- Very deep trees use an iterative traversal with an explicit stack to avoid stack overflow.

## Interview questions

### Tree vs graph: what is the difference?

A tree is a connected graph with no cycles: n nodes and exactly n - 1 edges, with one path between any two nodes. A graph can have cycles and disconnected parts.

### What is the height of a tree?

The number of edges on the longest path from the root to a leaf. A balanced binary tree with n nodes has height O(log n).

### What are the tree traversal orders?

Depth-first orders are preorder, inorder and postorder. Level order visits nodes level by level, which is breadth-first search.

## Related cards

- [Binary Tree](https://wonderium.dev/algorithms/binary-tree.md)
- [Binary Search Tree](https://wonderium.dev/algorithms/binary-search-tree.md)
- [AVL Tree](https://wonderium.dev/algorithms/avl-tree.md)
- [Graph](https://wonderium.dev/algorithms/graph.md)
- [Depth-First Search](https://wonderium.dev/algorithms/depth-first-search.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/tree
- Last updated: 2026-11-25
