Trees and Graphs are important non-linear data structures frequently covered in technical interviews and placement examinations. They are used to represent hierarchical relationships, networks, connections, and complex relationships between data elements. Understanding their basic concepts, terminology, types, operations, traversal techniques, and differences is essential for solving Data Structures and Algorithms (DSA) problems. In this article, you will learn the fundamentals of trees and graphs, their important algorithms, JavaScript implementations, time complexities, and commonly asked placement interview questions.
Table of Contents
What Are Trees and Graphs?
Trees and graphs are non-linear data structures used to organize and represent relationships between data elements.
Unlike arrays, stacks, and queues, which generally organize elements in a linear sequence, trees and graphs allow connections between elements in more complex ways.
- Trees: Represent hierarchical relationships using parent-child connections.
- Graphs: Represent relationships between connected elements using vertices and edges.
For example, a company's organizational structure can be represented using a tree, while a social network can be represented using a graph.
Both data structures are important for placement preparation because many interview problems involve searching, traversal, connectivity, shortest paths, and relationship management.
What Is a Tree Data Structure?
A Tree is a non-linear hierarchical data structure consisting of nodes connected through edges. The topmost node is called the root. Other nodes are connected through parent-child relationships.
A tree with n nodes contains exactly n - 1 edges.
Important properties of a tree include:
- A tree is connected and contains no cycles.
- Every node except the root has exactly one parent.
- A node can have zero or more children, depending on the type of tree.
- There is exactly one path between any two nodes in a tree.
Trees are commonly used in file systems, database indexing, searching algorithms, and compiler design.
Basic Terminology of Trees
Understanding tree terminology is important for solving tree-based interview questions.
- Node: A node is an individual element that stores data and references to other nodes.
- Root: The root is the topmost node of a tree. It does not have a parent.
- Parent: A parent is a node that has one or more child nodes.
- Child: A child is a node directly connected below another node.
- Leaf Node: A leaf node is a node that does not have any children.
- Sibling: Nodes that share the same parent are called siblings.
- Height: The height of a node is the number of edges in the longest downward path from that node to a leaf. The height of a tree is the height of its root.
- Depth: The depth of a node is the number of edges between the root and that node.
- Subtree: A subtree is a smaller tree formed by a node and all its descendants.
- Ancestor and Descendant: An ancestor is a node located above another node along its path to the root. A descendant is a node located below another node.
Types of Trees
Different types of trees are used to solve different programming problems.
1. General Tree: A general tree allows a node to have any number of children. It is useful for representing hierarchical structures such as directories and organizational charts.
2. Binary Tree: A binary tree is a tree in which each node can have at most two children, called the left child and right child.
3. Binary Search Tree (BST): A Binary Search Tree follows an ordering rule given below
- Values smaller than a node are stored in its left subtree.
- Values larger than a node are stored in its right subtree.
This structure supports efficient searching, insertion, and deletion when it is reasonably balanced.
4. Full Binary Tree: A full binary tree is a binary tree in which every node has either zero or exactly two children.
5. Complete Binary Tree: A complete binary tree has all levels completely filled except possibly the last level, which is filled from left to right.
6. Perfect Binary Tree: A perfect binary tree has exactly two children for every internal node, and all leaf nodes are at the same level.
7. Balanced Binary Tree: A balanced binary tree maintains its height within a controlled range to support efficient operations. Examples include AVL trees and Red-Black trees.
8. Heap Tree: A heap is a complete binary tree that follows a specific ordering property.
- Min Heap: The parent value is smaller than or equal to its children.
- Max Heap: The parent value is greater than or equal to its children.
Tree Traversal Techniques
Tree traversal is the process of visiting all nodes in a specific order. There are two main categories of tree traversal.
1. Depth-First Search (DFS): DFS explores one branch as far as possible before moving to another branch. It includes three common methods, as given below
- Preorder: Root → Left → Right.
- Inorder: Left → Root → Right.
- Postorder: Left → Right → Root.
For example, inorder traversal of a Binary Search Tree visits values in ascending order when the tree follows the standard BST ordering rules.
2. Breadth-First Search (BFS): BFS visits nodes level by level, starting from the root. It uses a queue to store nodes waiting to be processed. BFS is also called level-order traversal.
What Is a Graph Data Structure?
A Graph is a non-linear data structure consisting of vertices and edges.
- Vertex: Represents an individual element or point in a graph.
- Edge: Represents a connection between two vertices.
Graphs are used to represent relationships between different objects. For example, in a social networking application, users can be represented as vertices, and friendships or connections can be represented as edges.Unlike trees, graphs can contain cycles, and a vertex can have multiple connections.
A graph is generally represented as: [G = (V, E)]
Where:
- G represents the graph.
- V represents the set of vertices.
- E represents the set of edges.
Basic Terminology of Graphs
The following terms are commonly used in graph-related interview questions.
- Vertex: A vertex is an individual node in a graph.
- Edge: An edge represents a connection between two vertices.
- Adjacent Vertices: Two vertices are adjacent if an edge directly connects them.
- Degree: The degree of a vertex in an undirected graph is the number of edges connected to it.
- In-Degree: In a directed graph, in-degree is the number of edges entering a vertex.
- Out-Degree: Out-degree is the number of edges leaving a vertex.
- Path: A path is a sequence of vertices connected through edges.
- Cycle: A cycle is a path that starts and ends at the same vertex without repeating other vertices.
- Connected Graph: An undirected graph is connected if every vertex can be reached from every other vertex.
- Weighted Graph: A weighted graph assigns a numerical value or cost to each edge.
- Connected Component: A connected component is a maximal connected part of an undirected graph.
- Self-Loop: A self-loop is an edge that connects a vertex to itself.
Types of Graphs
Graphs can be classified according to their structure and connections.
1. Undirected Graph:An undirected graph contains edges without a specified direction. If vertex A is connected to vertex B, the connection can be traversed in both directions.
2. Directed Graph:
A directed graph contains edges with a specific direction. For example, an edge from A to B does not automatically mean that B is connected back to A.
3. Weighted Graph:
A weighted graph assigns values such as distance, cost, or time to its edges. It is commonly used in shortest-path problems.
4. Unweighted Graph:
An unweighted graph contains edges without assigned numerical weights.
5. Cyclic Graph:
A cyclic graph contains at least one cycle.
6. Acyclic Graph:
An acyclic graph does not contain any cycles.
7. Directed Acyclic Graph (DAG):
A DAG is a directed graph that contains no directed cycles. It is commonly used in task scheduling, dependency management, and build systems.
8. Complete Graph:
A complete undirected graph contains an edge between every pair of distinct vertices. For a simple complete undirected graph with n vertices.The number of edges is:[E = {n(n-1)}/{2}]
Graph Representation Methods
Graphs can be represented in different ways depending on the problem and memory requirements.
1. Adjacency Matrix
An adjacency matrix uses a two-dimensional array to represent connections between vertices. If an edge exists between two vertices, the corresponding matrix position contains 1. Otherwise, it contains 0.
For a weighted graph, the matrix can store edge weights instead.
For example, a graph with three vertices can be represented using the following JavaScript matrix:
// Represent a graph using an adjacency matrix.
const graph = [
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]
];
console.log(graph[0][1]);
Output:
1
The output is 1 because an edge exists between vertex 0 and vertex 1.
2. Adjacency List
An adjacency list stores the neighbors of each vertex. It is commonly implemented using arrays, objects, or maps.
// Represent a graph using an adjacency list.
const graph = {
A: ["B", "C"],
B: ["A", "D"],
C: ["A", "D"],
D: ["B", "C"]
};
console.log(graph.A);
Output:
[ 'B', 'C' ]
The output shows that vertices B and C are connected to vertex A.
Graph Traversal Techniques
Graph traversal is the process of visiting vertices in a graph.
The two most important graph traversal algorithms are DFS and BFS.
1. Depth-First Search (DFS)
Depth-First Search explores a path as deeply as possible before backtracking. It can be implemented using recursion or an explicit stack.
DFS is useful for:
- Detecting cycles.
- Finding connected components.
- Solving maze problems.
- Exploring graph paths.
- Performing topological sorting on a DAG.
2. Breadth-First Search (BFS)
Breadth-First Search explores all neighboring vertices before moving to the next level. It uses a queue to manage vertices waiting to be visited.
BFS is useful for:
- Finding shortest paths in unweighted graphs.
- Finding connected components.
- Level-based exploration.
- Solving minimum-step problems.
Common Tree and Graph Algorithms
Several algorithms are frequently asked in technical placement interviews.
1. Binary Search Tree Search: This algorithm searches for a value by comparing it with the current node. If the value is smaller, it moves to the left subtree. If it is larger, it moves to the right subtree.
2. Tree Traversal: Preorder, inorder, postorder, and level-order traversal are used to visit tree nodes in different sequences.
3. BFS Algorithm: BFS uses a queue to visit graph vertices level by level.
4. DFS Algorithm: DFS uses recursion or a stack to explore graph vertices deeply before backtracking.
5. Binary Search Tree Validation: This problem checks whether a given binary tree follows the Binary Search Tree ordering rules.
6. Lowest Common Ancestor (LCA): The Lowest Common Ancestor of two nodes is the lowest node in a tree that is an ancestor of both nodes.
7. Cycle Detection: Cycle detection determines whether a graph contains a cycle. Different approaches are used for directed and undirected graphs.
8. Topological Sorting: Topological sorting arranges the vertices of a Directed Acyclic Graph so that every directed edge from one vertex to another places the first vertex before the second.
9. Dijkstra's Algorithm: Dijkstra's algorithm finds shortest paths from a starting vertex to other vertices in a weighted graph with non-negative edge weights.
10. Minimum Spanning Tree: A Minimum Spanning Tree connects all vertices in a connected, weighted, undirected graph with the minimum possible total edge weight and no cycles. Kruskal's and Prim's algorithms are commonly used to find a Minimum Spanning Tree.
JavaScript Implementation Examples
The following examples demonstrate basic tree and graph algorithms commonly used in placement preparation.
1. Binary Tree Inorder Traversal
Inorder traversal visits the left subtree, then the current node, and finally the right subtree.
// Perform inorder traversal of a binary tree.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function inorder(root) {
if (root === null) {
return [];
}
return [
...inorder(root.left),
root.value,
...inorder(root.right)
];
}
const root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
console.log(inorder(root));
Output:
[ 5, 10, 15 ]
Explanation:
- The Node class creates a binary tree node.
- The inorder() function first visits the left subtree.
- It then adds the current node's value.
- Finally, it visits the right subtree.
- The output contains the values in inorder sequence.
2. Graph BFS Traversal
The following program demonstrates BFS using an adjacency list and a queue.
// Perform breadth-first search on a graph.
const graph = {
A: ["B", "C"],
B: ["A", "D"],
C: ["A", "E"],
D: ["B"],
E: ["C"]
};
function bfs(graph, start) {
const queue = [start];
const visited = new Set([start]);
const result = [];
while (queue.length > 0) {
const vertex = queue.shift();
result.push(vertex);
for (const neighbor of graph[vertex]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return result;
}
console.log(bfs(graph, "A"));
Output:
[ 'A', 'B', 'C', 'D', 'E' ]
Explanation:
- The graph object stores vertices and their neighboring vertices.
- The queue stores vertices waiting to be processed.
- The visited set prevents the same vertex from being visited more than once.
- The algorithm removes a vertex from the queue and checks its neighbors.
- Unvisited neighbors are added to the queue.
- The process continues until the queue becomes empty.
3. Graph DFS Traversal
The following program demonstrates DFS using recursion.
// Perform depth-first search on a graph.
const graph = {
A: ["B", "C"],
B: ["A", "D"],
C: ["A", "E"],
D: ["B"],
E: ["C"]
};
function dfs(graph, vertex, visited = new Set()) {
visited.add(vertex);
console.log(vertex);
for (const neighbor of graph[vertex]) {
if (!visited.has(neighbor)) {
dfs(graph, neighbor, visited);
}
}
}
dfs(graph, "A");
Output:
A
B
D
C
E
Explanation:
- The dfs() function starts from the given vertex.
- The current vertex is added to the visited set.
- It checks all neighboring vertices.
- If a neighbor has not been visited, the function calls itself recursively.
- The algorithm continues until all reachable vertices have been visited.
Note: These examples use shift() for simplicity. For large graphs, an array-based queue with a front index can avoid repeated shifting. Also, traversal order depends on the order in which neighbors are stored in the adjacency list.
Difference Between Trees and Graphs
Trees and graphs are both non-linear data structures, but they have different properties.
| Feature | Tree | Graph |
|---|---|---|
| Structure | Hierarchical | Network-based |
| Nodes | Called nodes | Called vertices |
| Connections | Parent-child relationships | General connections |
| Cycles | No cycles | May contain cycles |
| Root | Has one root in a rooted tree | No root required |
| Connectivity | Always connected when non-empty | May be disconnected |
| Paths | Exactly one path between any two vertices | May have multiple paths |
| Edges | n - 1 for a tree with n nodes | Depends on graph type |
| Direction | Usually represented with parent-child relationships | Can be directed or undirected |
| Applications | File systems, BSTs, DOM | Social networks, maps, routing |
A tree is a special type of connected, undirected graph that contains no cycles.
Time Complexity of Tree and Graph Operations
Understanding time complexity is important for technical interviews because interviewers often ask candidates to analyze the efficiency of their solutions.
Tree Operations
For a Binary Search Tree, the time complexity depends on whether the tree is balanced or skewed.
| Operation | Average Case | Worst Case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insertion | O(log n) | O(n) |
| Deletion | O(log n) | O(n) |
| Traversal | O(n) | O(n) |
Graph Operations
For a graph with V vertices and E edges represented using an adjacency list:
| Operation | Time Complexity |
|---|---|
| Add Vertex | O(1) average |
| Add Edge | O(1) average |
| Check Edge | O(degree of vertex) |
| BFS Traversal | O(V + E) |
| DFS Traversal | O(V + E) |
For an adjacency matrix, checking whether an edge exists takes O(1) time, but the matrix requires O(V²) space.
Here:
- V represents the number of vertices.
- E represents the number of edges.
- n represents the number of nodes in a tree.
Important Placement Interview Questions
The following questions are useful for preparing for technical interviews and placement examinations.
Basic Questions
- What is a tree data structure?
- What is a graph data structure?
- What is the difference between a tree and a graph?
- What are root, parent, child, and leaf nodes?
- What is the difference between a binary tree and a Binary Search Tree?
- What is a balanced binary tree?
- What is a directed graph?
- What is an undirected graph?
- What is an adjacency matrix?
- What is an adjacency list?
Intermediate Questions
- Explain preorder, inorder, and postorder traversal.
- What is the difference between BFS and DFS?
- How can you find the height of a binary tree?
- How can you check whether a binary tree is a BST?
- How can you find the lowest common ancestor of two nodes?
- How can you detect a cycle in a graph?
- What is topological sorting?
- What is the difference between a connected and disconnected graph?
- How do you find the shortest path in an unweighted graph?
- What is a Minimum Spanning Tree?
Common Coding Problems
- Find the maximum depth of a binary tree.
- Invert or mirror a binary tree.
- Validate a Binary Search Tree.
- Find the diameter of a binary tree.
- Perform level-order traversal.
- Find the lowest common ancestor.
- Count the number of connected components in a graph.
- Detect a cycle in a directed or undirected graph.
- Find the shortest path in an unweighted graph.
- Perform topological sorting of a DAG.
Common Mistakes to Avoid
- Confusing Trees and Graphs: Remember that every tree is a graph, but every graph is not a tree.
- Mixing Up Traversal Orders: Practice preorder, inorder, postorder, BFS, and DFS separately.
- Forgetting Visited Tracking: Use a visited set in graph traversal to avoid repeated visits and infinite loops caused by cycles.
- Ignoring Disconnected Components: A traversal starting from one vertex only visits the vertices reachable from that starting point.
- Ignoring Time Complexity: Always consider the number of vertices, edges, and tree height when analyzing an algorithm.
Frequently Asked Questions
1. What are trees and graphs in data structures?
Trees and graphs are non-linear data structures used to represent relationships between elements. Trees represent hierarchical relationships, while graphs represent general connections.
2. What is the main difference between a tree and a graph?
A tree is connected and has no cycles, while a graph can be connected or disconnected and may contain cycles.
3. What are BFS and DFS?
BFS explores vertices level by level using a queue, while DFS explores one path deeply before backtracking using recursion or a stack.
4. Which graph representation is better: adjacency matrix or adjacency list?
An adjacency list is generally more memory-efficient for sparse graphs, while an adjacency matrix provides constant-time edge lookup and is useful for dense graphs.
5. Which tree and graph topics are important for placements?
Binary Trees, Binary Search Trees, tree traversals, BFS, DFS, cycle detection, shortest paths, topological sorting, and Minimum Spanning Trees are important placement topics.
Conclusion
Trees and Graphs are essential non-linear data structures used to represent hierarchical and network-based relationships. Trees are useful for organizing hierarchical data, while graphs are suitable for representing complex connections between different elements. Understanding their terminology, types, representations, traversal methods, algorithms, and time complexities is important for solving DSA problems. Practicing common coding questions involving Binary Search Trees, BFS, DFS, shortest paths, and cycle detection will help build a strong foundation for technical placement interviews.
0 Comments