
In computer science, a Tree is a non-linear data structure used to represent hierarchical relationships. Unlike arrays, linked lists, stacks, and queues (which are linear), a tree organizes data in a hierarchy – just like a real tree with branches and leaves.
Example: Your computer’s file system (folders inside folders) is the best real-world example of a tree.
What is a Tree in Data Structure?
A Tree is made up of nodes connected by edges.
- Node → A single data element in the tree.
- Root Node → The top-most node (like the main folder).
- Parent Node → A node that has child nodes.
- Child Node → A node that comes from a parent.
- Leaf Node → A node with no children (like end folders/files).
- Edge → The connection between parent and child.
- Height of Tree → The length of the longest path from root to leaf.
Why Trees?
- Trees allow fast searching and sorting.
- Used in databases (B-Tree, B+ Tree).
- Helps in parsing expressions in compilers.
- Used in network routing algorithms.
- File systems, AI decision-making, XML/HTML parsing all use trees.
Types of Trees in Data Structures
There are several types of trees, but here are the most common:
- General Tree → Any node can have any number of children.
- Binary Tree → Each node can have at most 2 children (left and right).
- Binary Search Tree (BST) → A binary tree where:
- AVL Tree → A self-balancing binary search tree.
- Heap Tree → A special complete binary tree (used in priority queues).
- Trie → Used for string searching (like autocomplete in Google).
Example of a Binary Tree
10
/ \
20 30
/ \ /
40 50 60
- Root = 10
- Children of 10 = 20, 30
- Parent of 20 = 10
- Leaf nodes = 40, 50, 60
Tree Implementation Example in Java
class Node {
int data;
Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
public class BinaryTree {
Node root;
public BinaryTree() {
root = null;
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// Create tree nodes
tree.root = new Node(10);
tree.root.left = new Node(20);
tree.root.right = new Node(30);
tree.root.left.left = new Node(40);
tree.root.left.right = new Node(50);
System.out.println("Root Node: " + tree.root.data);
}
}
Applications of Trees
- Binary Search Tree → Fast searching & sorting.
- Heap → Used in priority-based scheduling.
- Trie → Auto-suggestions in search engines.
- Parse Tree → Compilers & expression evaluation.
- Decision Trees → Machine Learning & AI.
The Tree data structure is one of the most important concepts in computer science. It represents hierarchical data efficiently and is used in almost every advanced field – from databases to artificial intelligence.
If you are preparing for coding interviews, make sure you understand Binary Trees, Binary Search Trees, and Heaps, as they are the most frequently asked topics.