Tree in Data Structure: Terminology, Types, Examples & Applications

Chapter 60 Data Structure · Non-Linear Data Structures

Tree in Data Structure: Terminology, Types, Examples & Applications

Think about the folders on your laptop. One main folder can contain many smaller folders, and those folders can contain more files and folders. Everything is organised from the top to the bottom.

A tree in data structure works in a similar way. Students often get confused by words like root, parent, leaf, sibling, depth and height. In this chapter, we will learn them using the same simple diagram, then understand different types of trees, their real uses and a basic C program.

Quick Answer: What Is a Tree in Data Structure?

A tree is a non-linear, hierarchical data structure made of nodes connected by edges. It has one root node, parent-child relationships and no cycles. Except for the root, every node has exactly one parent. Trees are useful when information is naturally arranged in levels, such as folders, website elements and organisation charts.

01 / Understand the idea

Why Do We Need a Tree Data Structure?

Tree in Data Structure: Terminology, Types, Examples & Applications

Arrays and linked lists usually keep elements one after another. But real information is not always arranged in one straight line. For example, a college has departments, each department has courses, and each course has subjects. This is a hierarchy.

A tree stores this type of information naturally. One node can have children, and each child can have its own children. This makes it easier to represent categories, relationships and nested data.

Real-life example: In a folder structure, College is the main folder. It may contain Notes and Assignments. Inside Notes, you may have DSA and Java. The main folder acts like a root, while subfolders act like children.

Example of a Tree with Pictorial Representation

Consider the following tree containing seven nodes: A, B, C, D, E, F and G. We will use this one diagram throughout the chapter, so you can understand every term without memorising separate examples.

Explore the Tree

Seven-node binary tree showing root, parents and leaves A is the root; B and C are children of A; D and E are children of B; F is the right child of C; G is the left child of F. Four depth levels, 0 to 3. Level 0 Level 1 Level 2 Level 3 A B C D E F G
Figure 1: Our example tree. The root is A. Each line is an edge. D, E and G have no children, so they are leaf nodes. The longest root-to-leaf path is A → C → F → G.
7Nodes
6Edges
3Leaf nodes
3Height in edges

Tap a button to understand each part:

Root = A. A is the topmost node. It has no parent.

02 / Learn the vocabulary

Tree Terminology in Data Structure

These are the most important words for exam questions. Every example refers to Figure 1.

1. Node

A place that stores data. A, B, C, D, E, F and G are seven nodes.

2. Root

The topmost node, which has no parent. Here, A is the root.

3. Edge

The link between a parent and child. A–B is one edge. Our tree has six edges.

4. Parent

A node directly above a child. B is the parent of D and E.

5. Child

A node directly below a parent. B and C are children of A.

6. Siblings

Nodes with the same parent. B and C are siblings; D and E are also siblings.

7. Leaf (External) Node

A node without children. In Figure 1, D, E and G are leaves.

8. Internal (Non-Leaf) Node

A node with at least one child. A, B, C and F are internal nodes.

9. Ancestor

Any parent or higher family node. A, C and F are ancestors of G.

10. Descendant

A node below another node. F and G are descendants of C.

11. Subtree

A node together with all the nodes below it. The subtree rooted at C contains C, F and G.

12. Path

A sequence of connected nodes. A → C → F → G is a path containing three edges.

13. Degree of a Node

Its number of children. Degree(A) = 2; degree(C) = 1; degree(D) = 0.

14. Degree of a Tree

The maximum node degree in the tree. Our example has degree 2.

15. Depth

The number of edges from root to a node. Depth(A) = 0 and depth(G) = 3.

16. Height

The number of edges on the longest path down to a leaf. Height(A) = 3 and height(G) = 0.

Difference Between Level, Depth and Height

These three words can look similar, but they answer different questions. Depth counts edges from the root down to a node. Height counts edges from a node down to its deepest leaf. A level groups nodes at the same depth.

Level (root = 0) Nodes Example depth
0ADepth(A) = 0
1B, CDepth(B) = 1
2D, E, FDepth(F) = 2
3GDepth(G) = 3
Exam note: We are counting height in edges, so our tree height is 3 and a leaf has height 0. Some books count height or levels in nodes instead, giving 4 levels here. Some books also start level numbering at 1. Write your convention clearly.

One Important Formula

For every non-empty tree: Number of edges = Number of nodes − 1

Here, nodes = 7, so edges = 7 − 1 = 6. This rule works because every node except the root has exactly one parent connection.

03 / Recognise the shapes

Types of Tree in Data Structure with Examples

Trees are classified by how many children are allowed and how their nodes are arranged. Learn the differences below rather than memorising only names.

1. General Tree

A node may have any number of children. A folder can contain several subfolders.

    A
  / | \
 B  C  D
   / \
  E   F

2. Binary Tree

Each node has at most two children, called left and right. A node may have 0, 1 or 2 children.

     A
    / \
   B   C
  / \
 D   E

3. Full Binary Tree

Every node has either exactly two children or no children. No node has only one child.

     A
    / \
   B   C
  / \
 D   E

4. Perfect Binary Tree

Every internal node has two children and all leaves are on the same level. All levels are filled.

     A
    / \
   B   C
  / \ / \
 D  E F  G

5. Complete Binary Tree

All levels are filled except possibly the last. The last level fills from left to right, with no gaps.

     A
    / \
   B   C
  / \ /
 D  E F

6. Skewed (Degenerate) Tree

Each node has only one child. It looks like a linked list and can make searching slower.

 A
  \
   B
    \
     C
      \
       D
Quick memory trick: Full = 0 or 2 children. Perfect = all levels completely filled. Complete = last level may be unfinished, but nodes must fill from the left. A perfect binary tree is both full and complete.

7. Balanced Binary Tree

A balanced tree keeps its height under control, so it does not become a long chain. Different balanced-tree types use specific rules. For example, in an AVL tree, the heights of the left and right subtrees differ by at most one at every node.

8. Binary Search Tree (BST)

A BST is a binary tree with an ordering rule: values in the left subtree are smaller than the node, and values in the right subtree are larger (when keys are unique). This makes searching efficient when the tree stays reasonably balanced.

        50
       /  \
     30    70
    / \   / \
   20 40 60 80

To search for 60, compare it with 50. Since 60 is larger, go right to 70. Since 60 is smaller than 70, go left to 60. The value is found. This example needs only three node checks.

Other Important Tree Structures

Tree typeSimple ideaCommon use
Heap A complete binary tree with a parent-child priority rule Priority queues, heap sort
AVL tree Self-balancing binary search tree Maintaining efficient ordered searches
B-tree Balanced search tree where a node can contain several keys and children Database and file-system indexes
Trie Stores words or keys by following characters along paths Autocomplete and prefix searching
Expression tree Operators are internal nodes and operands are often leaves Expression evaluation, compilers

A binary tree and a binary search tree are not the same. Only BSTs follow the special key-ordering rule.

04 / Store and use a tree

How Is a Tree Represented in Memory?

1. Linked Representation

In a binary tree, each node can store its data plus a link to its left child and a link to its right child. If a child does not exist, its pointer is NULL. This representation is flexible for many tree shapes.

struct Node {
    char data;
    struct Node *left;
    struct Node *right;
};

2. Array Representation

A complete binary tree can be stored efficiently in an array. For a node at index i in a zero-based array, its left child is at 2*i+1 and its right child is at 2*i+2, if those indexes exist. This is why heaps are commonly stored in arrays.

Example: In the array [A, B, C, D, E, F], A is at index 0. Its left child B is at index 1 and its right child C is at index 2. This works neatly for a complete binary tree.

Basic Operations on a Tree

The operations depend on the type of tree. Common operations include creating a node, inserting or deleting a node, searching, finding height, and traversing the nodes.

Tree Traversal in Simple Language

Traversal means visiting every node in a chosen order. For a binary tree, the following are popular methods:

Traversal Rule Result on Figure 1
Preorder Root → Left → Right A B D E C F G
Inorder Left → Root → Right D B E A C G F
Postorder Left → Right → Root D E B G F C A
Level order Visit one level at a time, left to right A B C D E F G

Easy example: In preorder, start with A, explore its left subtree (B, D, E), and then its right subtree (C, F, G). That gives A B D E C F G.

05 / Working C example

Tree in Data Structure: C Program with Example

The program below creates the same binary tree shown in Figure 1. It counts nodes and leaves, finds height measured in edges, and prints preorder, inorder and postorder traversals. This is a basic binary tree, not necessarily a binary search tree.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    char data;
    struct Node *left, *right;
} Node;

Node *createNode(char value) {
    Node *node = malloc(sizeof *node);
    if (node == NULL) {
        puts("Memory allocation failed");
        exit(EXIT_FAILURE);
    }
    node->data = value;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int countNodes(const Node *root) {
    if (root == NULL) return 0;
    return 1 + countNodes(root->left)
             + countNodes(root->right);
}

int countLeaves(const Node *root) {
    if (root == NULL) return 0;
    if (root->left == NULL && root->right == NULL)
        return 1;
    return countLeaves(root->left)
         + countLeaves(root->right);
}

int heightEdges(const Node *root) {
    if (root == NULL) return -1;
    int left = heightEdges(root->left);
    int right = heightEdges(root->right);
    return 1 + (left > right ? left : right);
}

void preorder(const Node *root) {
    if (root == NULL) return;
    printf("%c ", root->data);
    preorder(root->left);
    preorder(root->right);
}

void inorder(const Node *root) {
    if (root == NULL) return;
    inorder(root->left);
    printf("%c ", root->data);
    inorder(root->right);
}

void postorder(const Node *root) {
    if (root == NULL) return;
    postorder(root->left);
    postorder(root->right);
    printf("%c ", root->data);
}

void freeTree(Node *root) {
    if (root == NULL) return;
    freeTree(root->left);
    freeTree(root->right);
    free(root);
}

int main(void) {
    Node *a = createNode('A');
    Node *b = createNode('B');
    Node *c = createNode('C');
    Node *d = createNode('D');
    Node *e = createNode('E');
    Node *f = createNode('F');
    Node *g = createNode('G');

    a->left = b;  a->right = c;
    b->left = d;  b->right = e;
    c->right = f; f->left = g;

    printf("Nodes: %d\n", countNodes(a));
    printf("Edges: %d\n", countNodes(a) - 1);
    printf("Leaves: %d\n", countLeaves(a));
    printf("Height (edges): %d\n", heightEdges(a));

    printf("Preorder:  "); preorder(a); putchar('\n');
    printf("Inorder:   "); inorder(a); putchar('\n');
    printf("Postorder: "); postorder(a); putchar('\n');

    freeTree(a);
    return 0;
}

Output

Nodes: 7
Edges: 6
Leaves: 3
Height (edges): 3
Preorder:  A B D E C F G
Inorder:   D B E A C G F
Postorder: D E B G F C A

How Does the Program Work?

  1. createNode() creates a node and sets its children to NULL.
  2. The assignments such as a->left = b connect parents and children.
  3. countNodes() returns 1 for the current node, plus nodes in its left and right subtrees.
  4. countLeaves() returns 1 when a node has no children.
  5. heightEdges() uses the longer child path. It returns −1 for an empty tree, so a leaf has height 0.
  6. The traversal functions print nodes in three different orders.
  7. freeTree() releases the memory when the program ends.

Run in VS Code: Save as tree.c, compile with gcc -std=c11 -Wall -Wextra -pedantic tree.c -o tree, then use .\tree.exe in Windows PowerShell.

Time and Space Complexity of Common Tree Operations

There is no single time complexity for every tree. It depends on its shape and the operation being performed.

Operation Typical time What affects it?
Visit all nodes (traversal) O(n) Every node is visited once.
Count nodes or leaves O(n) We inspect every node.
Find height (recursive) O(n) We inspect each node.
Search in a balanced BST O(log n) Tree height grows slowly.
Search in a skewed BST O(n) It may behave like a linked list.

Here n is the number of nodes. Recursive tree operations also use call-stack memory proportional to tree height: approximately O(h + 1) for a non-empty tree of height h measured in edges.

06 / Where trees are useful

Applications of Tree in Data Structure

1. Computer folders Folders and subfolders are arranged from a main directory into smaller directories.
2. Webpage structure The HTML DOM represents elements in parent-child relationships.
3. Database indexes B-trees and related structures can make searching large ordered collections efficient.
4. Autocomplete Tries help store words so programs can search by a prefix.
5. Priority queues Binary heaps organise values by priority and support efficient insertion and removal.
6. Compilers Syntax and expression trees represent the structure of code and expressions.

Advantages and Limitations of Trees

Advantages: Trees naturally represent hierarchical data, support different kinds of searching and can organise large datasets efficiently when the right tree type is selected.

Limitations: Pointers and memory management can be more complex than arrays, and a badly unbalanced search tree may become slow. The right representation and balancing rules matter.

Tree vs Graph vs Linked List

Structure Main idea Example
Tree Hierarchy; unique parent except root; no cycles Folder hierarchy
Graph General connections; may contain cycles Road or social network
Linked list Nodes connected in a linear sequence Playlist or list of tasks

Common Mistakes Students Should Avoid

  • Do not say every tree is a binary tree. A general tree may have more than two children.
  • Do not confuse the root with a leaf. The root has no parent; a leaf has no children. A single-node tree is both.
  • Do not confuse depth and height. Depth is counted from the root; height is counted toward the deepest leaf.
  • Do not confuse full, perfect and complete binary trees; their rules are different.
  • Do not assume every binary tree follows the BST smaller-left, larger-right rule.

Important Exam Questions with Answers

2 Marks: Define a Tree in Data Structure

A tree is a non-linear hierarchical data structure consisting of nodes connected by edges. It has one root, no cycles, and each non-root node has exactly one parent.

5 Marks: Explain Tree Terminology with an Example

Draw Figure 1 and label A as root, B and C as children of A, D, E and G as leaf nodes, and A, B, C and F as internal nodes. Explain parent, child, sibling, ancestor, descendant, depth, height and degree with these labels.

10 Marks: Explain Types and Applications of Trees

Start with the definition and an example diagram. Describe general, binary, full, perfect, complete, balanced, skewed and binary search trees. Add a brief comparison, tree representation, common operations and practical applications such as folder hierarchy, database indexes and expression trees.

Frequently Asked Questions

Is a tree a linear or non-linear data structure?

A tree is a non-linear data structure because a node can have several children and information is organised in branches rather than one sequence.

Can a tree contain a cycle?

No. In the usual rooted-tree definition, cycles are not allowed. If the underlying connections form a cycle, the structure is not a tree.

How many edges are in a tree with 10 nodes?

A non-empty tree with n nodes has n − 1 edges. So a tree with 10 nodes has 9 edges.

What is the difference between a binary tree and a BST?

A binary tree allows at most two children per node. A BST is a binary tree with an extra rule that places smaller keys to the left and larger keys to the right, assuming unique keys.

Quick Revision and Conclusion

A tree organises information from a root through parent-child connections. A node without children is a leaf. The depth of a node counts edges from the root, while its height counts edges to its deepest leaf.

For our example, remember 7 nodes, 6 edges, 3 leaves and height 3 edges. Once these basics are clear, binary trees, BSTs, heaps and tree traversal become much easier to study.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources