---
title: Applications of Tree in Data Structure With Examples
url: https://www.masaischool.com/resources/applications-of-tree-in-data-structure
description: Applications of tree in data structure and real life: file systems, DOM, B-tree indexes, compiler ASTs, router tries, decision trees, Huffman, with code.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# Applications of Tree in Data Structure: 7 Real Systems, Each With a Small Python Example

> **Short answer**
>
> Trees model anything hierarchical or searchable in log time: file systems and the HTML DOM use general trees, databases use B-trees, compilers build syntax trees, routers use tries, machine learning uses decision trees, and compression uses Huffman trees. Each application below has a short runnable example.

Most lists of tree applications give a bullet and a sentence. This page gives seven, and for each one a few lines of Python you can run, so you can see the tree doing the job. It also maps every application to the type of tree it uses, which is the form the question usually takes in exams and interviews.

All code ran on Python 3.9 on 1 December 2026. Statements about real systems follow the linked primary documentation. Vocabulary is in [tree data structure explained](https://www.masaischool.com/resources/tree-data-structure-explained), and Masai's longer post on the topic is [Applications of Tree Explained](https://www.masaischool.com/blog/applications-of-tree/) (page opened and live on 1 December 2026).

## Which tree for which application

The one-screen answer. Pick the row that matches your question and read the example below it.

| Application | Tree type | Why a tree | Example below |
|---|---|---|---|
| File systems | General tree (n-ary) | Folders inside folders | 1 |
| Web page structure (DOM) | General tree | Elements nested in elements | 2 |
| Database indexes | B-tree, a wide balanced tree | Few disk reads per lookup | 3 |
| Compilers and calculators | Expression tree, abstract syntax tree (AST) | Operator with operands as children | 4 |
| Router IP lookup, autocomplete | Trie ([trie explained](https://www.masaischool.com/resources/trie-data-structure-explained)) | Shared prefixes | 5 |
| Machine learning classification | Decision tree | Yes or no question at each node | 6 |
| Compression | Huffman tree | Frequent symbols get short codes | 7 |
| Priority scheduling | [Heap](https://www.masaischool.com/resources/heap-data-structure-explained) | Always the next most urgent item | See heap page |
| Ordered sets and maps | [Binary search tree](https://www.masaischool.com/resources/binary-search-tree-explained), AVL, red-black | Sorted data with O(log n) updates | See BST page |

## 1 and 2: File systems and the DOM

Your computer's folders form a tree: a folder is a node whose children are files and subfolders. Operations such as total size or search are recursive walks, which is why [recursion](https://www.masaischool.com/resources/what-is-recursion) and trees go together.# File system: a folder tree, total size computed recursively fs = {"name": "project", "size": 0, "kids": [ {"name": "README.md", "size": 2, "kids": []}, {"name": "src", "size": 0, "kids": [ {"name": "app.py", "size": 14, "kids": []}, {"name": "utils.py", "size": 6, "kids": []}]}, {"name": "data", "size": 0, "kids": [ {"name": "users.csv", "size": 120, "kids": []}]}]} def total(node): return node["size"] + sum(total(k) for k in node["kids"]) def show(node, depth=0): print(" " * depth + node["name"], f"({total(node)} KB)") for k in node["kids"]: show(k, depth + 1) show(fs)

Output:project (142 KB) README.md (2 KB) src (20 KB) app.py (14 KB) utils.py (6 KB) data (120 KB) users.csv (120 KB)

A web page is the same shape. The browser turns HTML into the [Document Object Model](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model), a tree of elements, and JavaScript walks it to find or change things. This sketch counts links and measures nesting depth in a tiny page tree.# DOM-like tree: find every link with a depth-first walk page = ("html", [("body", [("nav", [("a", [])]), ("main", [("p", []), ("a", []), ("div", [("a", [])])])])]) def count(node, tag): name, kids = node return (name == tag) + sum(count(k, tag) for k in kids) def depth(node): return 1 + max((depth(k) for k in node[1]), default=0) print("links:", count(page, "a"), "| max depth:", depth(page))

Output: links: 3 | max depth: 5

## 3: Databases and B-trees

Databases need to find one row among millions without reading the whole table. A B-tree keeps many keys in each node, so the tree is very wide and only a few levels tall; each level is one disk read. [PostgreSQL's documentation](https://www.postgresql.org/docs/current/indexes-types.html) states that CREATE INDEX makes a B-tree index by default and that B-trees handle equality and range queries on sortable data. A [B-tree](https://en.wikipedia.org/wiki/B-tree) is a self-balancing generalisation of a binary search tree. We do not run one here because a faithful B-tree is long; the idea is the BST from [binary search tree explained](https://www.masaischool.com/resources/binary-search-tree-explained) with many keys per node.

|  | Binary search tree | B-tree |
|---|---|---|
| Keys per node | 1 | Many |
| Height for a million keys | About 20 if balanced | A handful, depending on node width |
| Built for | Memory | Disk pages |
| Seen in | Ordered maps in language libraries | Database and file-system indexes |

## 4 and 5: Compilers and routers

A compiler or interpreter turns source code into an [abstract syntax tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree), where each operator is a node and its operands are children. Evaluating the expression is a postorder traversal: children first, then the operator. The same tree printed in postorder gives postfix notation.# Compiler-style expression tree for (2 + 3) * 4 - 6 / 2 import operator ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv} tree = ("-", ("*", ("+", 2, 3), 4), ("/", 6, 2)) # (operator, left, right) or a number def evaluate(n): if isinstance(n, (int, float)): return n op, l, r = n return ops[op](evaluate(l), evaluate(r)) # postorder: children first def to_postfix(n): if isinstance(n, (int, float)): return str(n) op, l, r = n return f"{to_postfix(l)} {to_postfix(r)} {op}" print(evaluate(tree)) print(to_postfix(tree))

Output:17.0 2 3 + 4 * 6 2 / -

Check: (2 + 3) * 4 is 20, 6 / 2 is 3, and 20 minus 3 is 17. Routers need the **longest prefix match**: given an address, find the most specific route. A binary trie over the address bits does it by walking bit by bit and remembering the last route seen. The routes and addresses here are made up for the demo; real routing tables are far larger.# Router-style longest prefix match with a binary trie of IP bits routes = {"10.0.0.0/8": "A", "10.1.0.0/16": "B", "10.1.2.0/24": "C", "0.0.0.0/0": "default"} def bits(ip, n=32): num = 0 for part in ip.split("."): num = num * 256 + int(part) return format(num, "032b")[:n] root = {} for cidr, hop in routes.items(): ip, length = cidr.split("/") node = root for b in bits(ip, int(length)): node = node.setdefault(b, {}) node["hop"] = hop def lookup(ip): node, best = root, root.get("hop") for b in bits(ip): if b not in node: break node = node[b] best = node.get("hop", best) # remember the longest match seen so far return best for ip in ["10.1.2.9", "10.1.9.9", "10.9.9.9", "8.8.8.8"]: print(ip, "->", lookup(ip))

Output:10.1.2.9 -> C 10.1.9.9 -> B 10.9.9.9 -> A 8.8.8.8 -> default

10.1.2.9 matches three routes (/8, /16 and /24) and the longest one, C, wins. Wikipedia explains the rule on its [longest prefix match](https://en.wikipedia.org/wiki/Longest_prefix_match) page.

## 6 and 7: Decision trees and Huffman coding

A **decision tree** asks a yes or no question at each node and ends in a decision at a leaf. Machine learning libraries learn the questions from data; the tree itself is the same shape you can write by hand. This one decides on a scholarship application using invented rules.# Decision tree by hand: should a student apply to a scholarship? tree = ("cgpa >= 7.5", ("family_income < 5 lakh", "apply", "maybe"), "skip") def decide(node, facts): if isinstance(node, str): return node question, yes, no = node return decide(yes if facts[question] else no, facts) print(decide(tree, {"cgpa >= 7.5": True, "family_income < 5 lakh": True})) print(decide(tree, {"cgpa >= 7.5": True, "family_income < 5 lakh": False})) print(decide(tree, {"cgpa >= 7.5": False}))

Output:apply maybe skip

**Huffman coding** compresses text by giving frequent letters short bit codes. It builds a tree by repeatedly merging the two rarest subtrees, using a [heap](https://www.masaischool.com/resources/heap-data-structure-explained); the path from root to a letter, 0 for left and 1 for right, is its code. For abracadabra, the frequent a gets one bit.import heapq from collections import Counter text = "abracadabra" freq = Counter(text) heap = [(n, i, ch) for i, (ch, n) in enumerate(sorted(freq.items()))] heapq.heapify(heap) nxt = len(heap) while len(heap) > 1: n1, _, a = heapq.heappop(heap) # two rarest subtrees n2, _, b = heapq.heappop(heap) heapq.heappush(heap, (n1 + n2, nxt, (a, b))) nxt += 1 tree = heap[0][2] codes = {} def walk(node, path=""): if isinstance(node, str): codes[node] = path or "0" else: walk(node[0], path + "0") walk(node[1], path + "1") walk(tree) encoded = "".join(codes[c] for c in text) print(dict(sorted(codes.items()))) print("fixed 8-bit:", len(text) * 8, "bits | huffman:", len(encoded), "bits")

Output:{'a': '0', 'b': '110', 'c': '100', 'd': '101', 'r': '111'} fixed 8-bit: 88 bits | huffman: 23 bits

That is 23 bits instead of 88, before counting the cost of storing the code table. See [Huffman coding](https://en.wikipedia.org/wiki/Huffman_coding) for the full algorithm.

## How to answer this in an exam or interview

- Name the **tree type** first, then the application: "a trie for IP routing", not just "routers".
- Say what property is used: ordering (BST), balance (B-tree), prefix sharing (trie), hierarchy (file system), recursion (AST).
- Give one runnable or concrete case, such as the examples above, instead of a list of five nouns.
- For "applications of binary tree" specifically, the strongest answers are expression trees, binary search trees, heaps and Huffman trees. Folders and the DOM are general trees because a node can have more than two children.

Next, read [graph applications](https://www.masaischool.com/resources/applications-of-graph-in-data-structure) to see where trees stop and graphs start, the [linked list](https://www.masaischool.com/resources/linked-list-explained) page for pointer-based structures, and [DSA interview questions](https://www.masaischool.com/resources/dsa-interview-questions) for practice. Parent path: [DSA learning path](https://www.masaischool.com/resources/data-structures-and-algorithms).

## Frequently asked questions

### What are the applications of tree in data structure?

Trees are used for file systems and the HTML DOM (hierarchies), database and file indexes (B-trees), ordered sets and maps (balanced BSTs), priority queues (heaps), compiler syntax trees, router and autocomplete lookups (tries), decision trees in machine learning and Huffman compression.

### What are the applications of binary tree?

Binary trees are used in binary search trees for fast ordered lookup, heaps for priority queues, expression trees for evaluating arithmetic, Huffman trees for compression, and decision trees with yes or no splits. A general file-system tree is not binary because folders hold many children.

### What are the real-life applications of trees?

Folder structures on your phone or laptop, the layout of a web page, the index that lets a database find a row quickly, the route lookup inside a router, spell and search suggestions, and the compression behind some file formats all rely on tree structures.

### Why are trees used instead of arrays or lists?

Trees model hierarchy naturally and, when balanced, give O(log n) search, insert and delete while keeping data ordered. A sorted array searches fast but inserts slowly; an unsorted list inserts fast but searches slowly. A balanced tree is a compromise.

### Where is a B-tree used?

In database and file-system indexes. PostgreSQL's documentation says its default index type is the B-tree. Wide nodes mean a lookup touches only a few disk pages even for millions of rows.

### What tree is used in a compiler?

A compiler parses source code into an abstract syntax tree, where operators and statements are internal nodes and variables and constants are leaves. Later stages such as type checking and code generation walk this tree, usually in postorder.

### Is a decision tree in machine learning a data structure?

Yes, it is a tree whose internal nodes hold a question about a feature and whose leaves hold a prediction. What differs from the exam topic is that libraries learn the questions from training data rather than a programmer writing them.
