Introduction to Tree Data Structure
Last Updated :
04 Mar, 2025
Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.
- Folder structure in an operating system.
- Tag structure in an HTML (root tag the as html tag) or XML document.
The topmost node of the tree is called the root, and the nodes below it are called the child nodes. Each node can have multiple child nodes, and these child nodes can also have their own child nodes, forming a recursive structure.

Basic Terminologies In Tree Data Structure:
- Parent Node: The node which is an immediate predecessor of a node is called the parent node of that node. {B} is the parent node of {D, E}.
- Child Node: The node which is the immediate successor of a node is called the child node of that node. Examples: {D, E} are the child nodes of {B}.
- Root Node: The topmost node of a tree or the node which does not have any parent node is called the root node. {A} is the root node of the tree. A non-empty tree must contain exactly one root node and exactly one path from the root to all other nodes of the tree.
- Leaf Node or External Node: The nodes which do not have any child nodes are called leaf nodes. {I, J, K, F, G, H} are the leaf nodes of the tree.
- Ancestor of a Node: Any predecessor nodes on the path of the root to that node are called Ancestors of that node. {A,B} are the ancestor nodes of the node {E}
- Descendant: A node x is a descendant of another node y if and only if y is an ancestor of x.
- Sibling: Children of the same parent node are called siblings. {D,E} are called siblings.
- Level of a node: The count of edges on the path from the root node to that node. The root node has level 0.
- Internal node: A node with at least one child is called Internal Node.
- Neighbour of a Node: Parent or child nodes of that node are called neighbors of that node.
- Subtree: Any node of the tree along with its descendant.

Basic Terminologies In Tree
Why Tree is considered a non-linear data structure?
The data in a tree are not stored in a sequential manner i.e., they are not stored linearly. Instead, they are arranged on multiple levels or we can say it is a hierarchical structure. For this reason, the tree is considered to be a non-linear data structure.
We strongly recommend to study a Binary Tree first as a Binary Tree has structure and code implementation compared to a general tree.
Representation of Tree Data Structure:
A tree consists of a root node, and zero or more subtrees T1, T2, … , Tk such that there is an edge from the root node of the tree to the root node of each subtree. Subtree of a node X consists of all the nodes which have node X as the ancestor node.

Representation of Tree Data Structure
Representation of a Node in Tree Data Structure:
A tree can be represented using a collection of nodes. Each of the nodes can be represented with the help of class or structs. Below is the representation of Node in different languages:
C++
class Node {
public:
int data;
Node* first_child;
Node* second_child;
Node* third_child;
.
.
.
Node* nth_child;
};
C
struct Node {
int data;
struct Node* first_child;
struct Node* second_child;
struct Node* third_child;
.
.
.
struct Node* nth_child;
};
Java
public static class Node {
int data;
Node first_child;
Node second_child;
Node third_child;
.
.
.
Node nth_child;
}
Python
class Node:
def __init__(self, data):
self.data = data
self.children = []
JavaScript
class Node {
constructor(data) {
this.data = data;
this.children = [];
}
}
Importance for Tree Data Structure:
One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: The DOM model of an HTML page is also tree where we have html tag as root, head and body its children and these tags, then have their own children.Please refer Applications, Advantages and Disadvantages of Tree for details.
Types of Tree data structures:
Tree data structure can be classified into three types based upon the number of children each node of the tree can have. The types are:
- Binary tree: In a binary tree, each node can have a maximum of two children linked to it. Some common types of binary trees include full binary trees, complete binary trees, balanced binary trees, and degenerate or pathological binary trees. Examples of Binary Tree are Binary Search Tree and Binary Heap.
- Ternary Tree: A Ternary Tree is a tree data structure in which each node has at most three child nodes, usually distinguished as “left”, “mid” and “right”.
- N-ary Tree or Generic Tree: Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes.
Please refer Types of Trees in Data Structures for details.
Basic Operations Of Tree Data Structure:
- Create – create a tree in the data structure.
- Insert − Inserts data in a tree.
- Search − Searches specific data in a tree to check whether it is present or not.
- Traversal:
Implementation of Tree Data Structure:
C++
// C++ program to demonstrate some of the above
// terminologies
#include <bits/stdc++.h>
using namespace std;
// Function to add an edge between vertices x and y
void addEdge(int x, int y, vector<vector<int> >& adj)
{
adj[x].push_back(y);
adj[y].push_back(x);
}
// Function to print the parent of each node
void printParents(int node, vector<vector<int> >& adj,
int parent)
{
// current node is Root, thus, has no parent
if (parent == 0)
cout << node << "->Root" << endl;
else
cout << node << "->" << parent << endl;
// Using DFS
for (auto cur : adj[node])
if (cur != parent)
printParents(cur, adj, node);
}
// Function to print the children of each node
void printChildren(int Root, vector<vector<int> >& adj)
{
// Queue for the BFS
queue<int> q;
// pushing the root
q.push(Root);
// visit array to keep track of nodes that have been
// visited
int vis[adj.size()] = { 0 };
// BFS
while (!q.empty()) {
int node = q.front();
q.pop();
vis[node] = 1;
cout << node << "-> ";
for (auto cur : adj[node])
if (vis[cur] == 0) {
cout << cur << " ";
q.push(cur);
}
cout << endl;
}
}
// Function to print the leaf nodes
void printLeafNodes(int Root, vector<vector<int> >& adj)
{
// Leaf nodes have only one edge and are not the root
for (int i = 1; i < adj.size(); i++)
if (adj[i].size() == 1 && i != Root)
cout << i << " ";
cout << endl;
}
// Function to print the degrees of each node
void printDegrees(int Root, vector<vector<int> >& adj)
{
for (int i = 1; i < adj.size(); i++) {
cout << i << ": ";
// Root has no parent, thus, its degree is equal to
// the edges it is connected to
if (i == Root)
cout << adj[i].size() << endl;
else
cout << adj[i].size() - 1 << endl;
}
}
// Driver code
int main()
{
// Number of nodes
int N = 7, Root = 1;
// Adjacency list to store the tree
vector<vector<int> > adj(N + 1, vector<int>());
// Creating the tree
addEdge(1, 2, adj);
addEdge(1, 3, adj);
addEdge(1, 4, adj);
addEdge(2, 5, adj);
addEdge(2, 6, adj);
addEdge(4, 7, adj);
// Printing the parents of each node
cout << "The parents of each node are:" << endl;
printParents(Root, adj, 0);
// Printing the children of each node
cout << "The children of each node are:" << endl;
printChildren(Root, adj);
// Printing the leaf nodes in the tree
cout << "The leaf nodes of the tree are:" << endl;
printLeafNodes(Root, adj);
// Printing the degrees of each node
cout << "The degrees of each node are:" << endl;
printDegrees(Root, adj);
return 0;
}
Java
// java code for above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to print the parent of each node
public static void
printParents(int node, Vector<Vector<Integer> > adj,
int parent)
{
// current node is Root, thus, has no parent
if (parent == 0)
System.out.println(node + "->Root");
else
System.out.println(node + "->" + parent);
// Using DFS
for (int i = 0; i < adj.get(node).size(); i++)
if (adj.get(node).get(i) != parent)
printParents(adj.get(node).get(i), adj,
node);
}
// Function to print the children of each node
public static void
printChildren(int Root, Vector<Vector<Integer> > adj)
{
// Queue for the BFS
Queue<Integer> q = new LinkedList<>();
// pushing the root
q.add(Root);
// visit array to keep track of nodes that have been
// visited
int vis[] = new int[adj.size()];
Arrays.fill(vis, 0);
// BFS
while (q.size() != 0) {
int node = q.peek();
q.remove();
vis[node] = 1;
System.out.print(node + "-> ");
for (int i = 0; i < adj.get(node).size(); i++) {
if (vis[adj.get(node).get(i)] == 0) {
System.out.print(adj.get(node).get(i)
+ " ");
q.add(adj.get(node).get(i));
}
}
System.out.println();
}
}
// Function to print the leaf nodes
public static void
printLeafNodes(int Root, Vector<Vector<Integer> > adj)
{
// Leaf nodes have only one edge and are not the
// root
for (int i = 1; i < adj.size(); i++)
if (adj.get(i).size() == 1 && i != Root)
System.out.print(i + " ");
System.out.println();
}
// Function to print the degrees of each node
public static void
printDegrees(int Root, Vector<Vector<Integer> > adj)
{
for (int i = 1; i < adj.size(); i++) {
System.out.print(i + ": ");
// Root has no parent, thus, its degree is
// equal to the edges it is connected to
if (i == Root)
System.out.println(adj.get(i).size());
else
System.out.println(adj.get(i).size() - 1);
}
}
// Driver code
public static void main(String[] args)
{
// Number of nodes
int N = 7, Root = 1;
// Adjacency list to store the tree
Vector<Vector<Integer> > adj
= new Vector<Vector<Integer> >();
for (int i = 0; i < N + 1; i++) {
adj.add(new Vector<Integer>());
}
// Creating the tree
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(1).add(3);
adj.get(3).add(1);
adj.get(1).add(4);
adj.get(4).add(1);
adj.get(2).add(5);
adj.get(5).add(2);
adj.get(2).add(6);
adj.get(6).add(2);
adj.get(4).add(7);
adj.get(7).add(4);
// Printing the parents of each node
System.out.println("The parents of each node are:");
printParents(Root, adj, 0);
// Printing the children of each node
System.out.println(
"The children of each node are:");
printChildren(Root, adj);
// Printing the leaf nodes in the tree
System.out.println(
"The leaf nodes of the tree are:");
printLeafNodes(Root, adj);
// Printing the degrees of each node
System.out.println("The degrees of each node are:");
printDegrees(Root, adj);
}
}
// This code is contributed by rj13to.
Python
from collections import deque
# Function to add an edge between vertices x and y
def addEdge(x, y, adj):
adj[x].append(y)
adj[y].append(x)
# Function to print the parent of each node
def printParents(node, adj, parent):
# current node is Root, thus, has no parent
if parent == 0:
print("{}->Root".format(node))
else:
print("{}->{}".format(node, parent))
# Using DFS
for cur in adj[node]:
if cur != parent:
printParents(cur, adj, node)
# Function to print the children of each node
def printChildren(Root, adj):
# Queue for the BFS
q = deque()
# pushing the root
q.append(Root)
# visit array to keep track of nodes that have been
# visited
vis = [0] * len(adj)
# BFS
while q:
node = q.popleft()
vis[node] = 1
print("{}->".format(node)),
for cur in adj[node]:
if vis[cur] == 0:
print(cur),
q.append(cur)
print()
# Function to print the leaf nodes
def printLeafNodes(Root, adj):
# Leaf nodes have only one edge and are not the root
for i in range(1, len(adj)):
if len(adj[i]) == 1 and i != Root:
print(i),
# Function to print the degrees of each node
def printDegrees(Root, adj):
for i in range(1, len(adj)):
print(i, ":"),
# Root has no parent, thus, its degree is equal to
# the edges it is connected to
if i == Root:
print(len(adj[i]))
else:
print(len(adj[i]) - 1)
# Driver code
N = 7
Root = 1
# Adjacency list to store the tree
adj = [[] for _ in range(N + 1)]
# Creating the tree
addEdge(1, 2, adj)
addEdge(1, 3, adj)
addEdge(1, 4, adj)
addEdge(2, 5, adj)
addEdge(2, 6, adj)
addEdge(4, 7, adj)
# Printing the parents of each node
print("The parents of each node are:")
printParents(Root, adj, 0)
# Printing the children of each node
print("The children of each node are:")
printChildren(Root, adj)
# Printing the leaf nodes in the tree
print("The leaf nodes of the tree are:")
printLeafNodes(Root, adj)
# Printing the degrees of each node
print("The degrees of each node are:")
printDegrees(Root, adj)
C#
using System;
using System.Collections.Generic;
class GfG
{
static void PrintParents(int node, List<List<int>> adj, int parent)
{
if (parent == 0)
{
Console.WriteLine($"{node} -> Root");
}
else
{
Console.WriteLine($"{node} -> {parent}");
}
foreach (int cur in adj[node])
{
if (cur != parent)
{
PrintParents(cur, adj, node);
}
}
}
static void PrintChildren(int Root, List<List<int>> adj)
{
Queue<int> q = new Queue<int>();
q.Enqueue(Root);
bool[] vis = new bool[adj.Count];
while (q.Count > 0)
{
int node = q.Dequeue();
vis[node] = true;
Console.Write($"{node} -> ");
foreach (int cur in adj[node])
{
if (!vis[cur])
{
Console.Write($"{cur} ");
q.Enqueue(cur);
}
}
Console.WriteLine();
}
}
static void PrintLeafNodes(int Root, List<List<int>> adj)
{
for (int i = 0; i < adj.Count; i++)
{
if (adj[i].Count == 1 && i != Root)
{
Console.Write($"{i} ");
}
}
Console.WriteLine();
}
static void PrintDegrees(int Root, List<List<int>> adj)
{
for (int i = 1; i < adj.Count; i++)
{
Console.Write($"{i}: ");
if (i == Root)
{
Console.WriteLine(adj[i].Count);
}
else
{
Console.WriteLine(adj[i].Count - 1);
}
}
}
static void Main(string[] args)
{
int N = 7;
int Root = 1;
List<List<int>> adj = new List<List<int>>();
for (int i = 0; i <= N; i++)
{
adj.Add(new List<int>());
}
adj[1].AddRange(new int[] { 2, 3, 4 });
adj[2].AddRange(new int[] { 1, 5, 6 });
adj[4].Add(7);
Console.WriteLine("The parents of each node are:");
PrintParents(Root, adj, 0);
Console.WriteLine("The children of each node are:");
PrintChildren(Root, adj);
Console.WriteLine("The leaf nodes of the tree are:");
PrintLeafNodes(Root, adj);
Console.WriteLine("The degrees of each node are:");
PrintDegrees(Root, adj);
}
}
JavaScript
// Number of nodes
let n = 7, root = 1;
// Adjacency list to store the tree
let adj = new Array(n + 1).fill(null).map(() => []);
// Creating the tree
addEdge(1, 2, adj);
addEdge(1, 3, adj);
addEdge(1, 4, adj);
addEdge(2, 5, adj);
addEdge(2, 6, adj);
addEdge(4, 7, adj);
// Function to add an edge between vertices x and y
function addEdge(x, y, arr) {
arr[x].push(y);
arr[y].push(x);
}
// Function to print the parent of each node
function printParents(node, arr, parent) {
// current node is Root, thus, has no parent
if (parent == 0)
console.log(`${node}->root`);
else
console.log(`${node}->${parent}`);
// Using DFS
for (let cur of arr[node])
if (cur != parent)
printParents(cur, arr, node);
}
// Function to print the children of each node
function printChildren(root, arr) {
// Queue for the BFS
let q = [];
// pushing the root
q.push(root);
// visit array to keep track of nodes
// that have been visited
let vis = new Array(arr.length).fill(0);
// BFS
while (q.length > 0) {
let node = q.shift();
vis[node] = 1;
console.log(`${node}-> `);
for (let cur of arr[node])
if (vis[cur] == 0) {
console.log(cur + " ");
q.push(cur);
}
console.log("\n");
}
}
// Function to print the leaf nodes
function printLeafNodes(root, arr) {
// Leaf nodes have only one edge
// and are not the root
for (let i = 1; i < arr.length; i++)
if (arr[i].length == 1 &&
i != root)
console.log(i + " ");
console.log("\n");
}
// Function to print the degrees of each node
function printDegrees(Root, arr) {
for (let i = 1; i < arr.length; i++) {
console.log(`${i}: `);
// Root has no parent, thus, its degree is equal to
// the edges it is connected to
if (i == root)
console.log(arr[i].length + "\n");
else
console.log(arr[i].length - 1 + "\n");
}
}
// Function to print the tree in a hierarchical format
function printTree(node, arr, parent, level) {
// Indent based on the level of the node
console.log(" ".repeat(level) + "└── " + node);
// Recursively print children
for (let cur of arr[node])
if (cur != parent)
printTree(cur, arr, node, level + 1);
}
// Driver code
// Printing the tree in a hierarchical format
console.log("Tree Structure:");
printTree(root, adj, 0, 0);
// Printing the parents of each node
console.log("\nThe parents of each node are:");
printParents(root, adj, 0);
// Printing the children of each node
console.log("\nThe children of each node are:");
printChildren(root, adj);
// Printing the leaf nodes in the tree
console.log("\nThe leaf nodes of the tree are:");
printLeafNodes(root, adj);
// Printing the degrees of each node
console.log("\nThe degrees of each node are:");
printDegrees(root, adj);
OutputThe parents of each node are:
1->Root
2->1
5->2
6->2
3->1
4->1
7->4
The children of each node are:
1-> 2 3 4
2-> 5 6
3->
4-> 7
5->
6->
7->
The leaf nodes of the tree are:
3 5 6 7
The degrees o...
Properties of Tree Data Structure:
Number of edges: An edge can be defined as the connection between two nodes. If a tree has N nodes then it will have (N-1) edges. There is only one path from each node to any other node of the tree.
Depth of a node: The depth of a node is defined as the length of the path from the root to that node. Each edge adds 1 unit of length to the path. So, it can also be defined as the number of edges in the path from the root of the tree to the node.
- Height of a node: The height of a node can be defined as the length of the longest path from the node to a leaf node of the tree.
- Height of the Tree: The height of a tree is the length of the longest path from the root of the tree to a leaf node of the tree.
- Degree of a Node: The total count of subtrees attached to that node is called the degree of the node. The degree of a leaf node must be 0. The degree of a tree is the maximum degree of a node among all the nodes in the tree.
Easy Problem On Tree in JavaScript
Medium Problem On Tree in JavaScript
Similar Reads
Introduction to Tree Data Structure
Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree. Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) o
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss all the tree travers
7 min read
Applications of tree data structure
A tree is a type of data structure that represents a hierarchical relationship between data elements, called nodes. The top node in the tree is called the root, and the elements below the root are called child nodes. Each child node may have one or more child nodes of its own, forming a branching st
4 min read
Advantages and Disadvantages of Tree
Tree is a non-linear data structure. It consists of nodes and edges. A tree represents data in a hierarchical organization. It is a special type of connected graph without any cycle or circuit. Advantages of Tree:Efficient searching: Trees are particularly efficient for searching and retrieving data
2 min read
Difference between an array and a tree
Array:An array is a collection of homogeneous(same type) data items stored in contiguous memory locations. For example, if an array is of type âintâ, it can only store integer elements and cannot allow the elements of other types such as double, float, char, etc. The array is a linear data structure
3 min read
Inorder Tree Traversal without Recursion
Given a binary tree, the task is to perform in-order traversal of the tree without using recursion. Example: Input: Output: 4 2 5 1 3Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3 Input: Output: 1 7 10 8 6 10 5 6Explanation: Inorder traversal (Left->Root->Rig
8 min read
Types of Trees in Data Structures
A tree in data structures is a hierarchical data structure that consists of nodes connected by edges. It is used to represent relationships between elements, where each node holds data and is connected to other nodes in a parent-child relationship. Types of Trees The main types of trees in data stru
4 min read
Generic Trees (N-ary Tree)
Introduction to Generic Trees (N-ary Trees)
Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and t
5 min read
Inorder traversal of an N-ary Tree
Given an N-ary tree containing, the task is to print the inorder traversal of the tree. Examples:Â Input: N = 3Â Â Output: 5 6 2 7 3 1 4Input: N = 3Â Â Output: 2 3 5 1 4 6Â Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finall
6 min read
Preorder Traversal of an N-ary Tree
Given an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree. Examples: Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 Output: 1 2 5 10 6 11 12 13 3 4 7 8 9 Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 O
14 min read
Iterative Postorder Traversal of N-ary Tree
Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We wi
10 min read
Level Order Traversal of N-ary Tree
Given an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line. Examples: Input: Output: 13 2 45 6Explanation: At level 1: only 1 is present.At level 2: 3, 2, 4 is presentAt level 3: 5, 6 is present Input: Output: 12 3 4 56 7 8 9 1011 12 1314Ex
11 min read
ZigZag Level Order Traversal of an N-ary Tree
Given a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow
8 min read
Binary Tree
Introduction to Binary Tree
Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Representation of Binary TreeEach node in a Binar
15+ min read
Properties of Binary Tree
This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levels Note: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A binary tree can have at most
4 min read
Applications, Advantages and Disadvantages of Binary Tree
A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation)
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Complete Binary Tree
We know a tree is a non-linear data structure. It has no limitation on the number of children. A binary tree has a limitation as any node of the tree has at most two children: a left and a right child. What is a Complete Binary Tree?A complete binary tree is a special type of binary tree where all t
7 min read
Perfect Binary Tree
What is a Perfect Binary Tree? A perfect binary tree is a special type of binary tree in which all the leaf nodes are at the same depth, and all non-leaf nodes have two children. In simple terms, this means that all leaf nodes are at the maximum depth of the tree, and the tree is completely filled w
4 min read