0% found this document useful (0 votes)
40 views29 pages

Document Sattu

- Sequential search checks each element in a collection sequentially until the target is found or the entire collection has been searched. It can be less efficient for large datasets. Binary search is only applicable to sorted collections and repeatedly divides the search space in half with each step. - A linked list stores elements in nodes that point to the next node. Common types are singly, doubly, and circular linked lists. Linked lists allow efficient insertion and deletion but random access is slow. Algorithms were provided to insert and delete nodes from a singly linked list. - Searching algorithms like linear and binary search were implemented in C. Linear search has O(n) time complexity while binary search has improved O(log n) time

Uploaded by

reetakamboj278
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views29 pages

Document Sattu

- Sequential search checks each element in a collection sequentially until the target is found or the entire collection has been searched. It can be less efficient for large datasets. Binary search is only applicable to sorted collections and repeatedly divides the search space in half with each step. - A linked list stores elements in nodes that point to the next node. Common types are singly, doubly, and circular linked lists. Linked lists allow efficient insertion and deletion but random access is slow. Algorithms were provided to insert and delete nodes from a singly linked list. - Searching algorithms like linear and binary search were implemented in C. Linear search has O(n) time complexity while binary search has improved O(log n) time

Uploaded by

reetakamboj278
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

ASSIGNMENT-1

1-What do you mean by searching? Explain


sequential search and binary search with help of
examples
Searching is the process of finding a particular item or value in a collection of data. Two common
search algorithms are sequential search and binary search.

1. **Sequential Search:**

- **Definition:** In a sequential search, each element in the collection is checked one by one
until the desired item is found or the entire collection has been searched.

- **Example:** Imagine you have an unsorted list of numbers [5, 12, 8, 3, 20, 7], and you want
to find the value 20.

- **Process:** Start from the beginning and check each element until you find 20. In this case,
you would check 5, 12, 8, 3, 20 (found).

2. **Binary Search:**

- **Definition:** Binary search is used on sorted collections. It involves repeatedly dividing the
search range in half until the value is found.

- **Example:** Consider a sorted list [3, 5, 7, 8, 12, 20] and you want to find the value 8.

- **Process:** Begin with the entire list, compare the middle element (7) with the target (8). Since 8
is greater, focus on the right half [8, 12, 20] and repeat. Now, compare 12 with 8. Move to the left
half [8] and find the target.

**Summary:**

- Sequential search is applicable to both sorted and unsorted lists but can be less efficient for large
datasets.

- Binary search is efficient for sorted lists but requires the data to be sorted beforehand. It's a
divideand-conquer approach that reduces the search space by half with each step.
2-Define linked list .what are the types of linked
list ? What are the ways of implementing linked
list state the advantages of circular list aver
building linked list.
**Linked List:**

A linked list is a linear data structure where elements are stored in nodes, and each node points to
the next node in the sequence. Unlike arrays, elements in a linked list are not stored in contiguous
memory locations.

**Types of Linked Lists:**

1. **Singly Linked List:** Each node points to the next node in the sequence.

2. **Doubly Linked List:** Each node has pointers to both the next and the previous nodes.

3. **Circular Linked List:** The last node points back to the first node, forming a circle.

**Ways of Implementing Linked List:**

1. **Pointer-based implementation:** Nodes are represented using pointers to the next (and
previous in the case of a doubly linked list) node.

2. **Array-based implementation:** Nodes are stored in an array, and each node contains an
index pointing to the next node.

**Advantages of Circular Linked List:**

1. **Efficient for Certain Operations:** Circular linked lists are useful when you need to
repeatedly traverse the entire list since there is no distinct end.

2. **Space Efficiency:** In a circular linked list, the last node points to the first, saving memory
compared to a linear singly linked list.

3. **Implementation of Circular Buffers:** Circular linked lists are used in implementing


circular buffers, which have applications in managing data streams.

**Building a Linked List:**

1. **Define the Node

Structure:** ```python class

Node:

def __init__(self, data):


self.data = data

self.next = None

```

2. **Create Nodes and Link

Them:** ```python node1 =

Node(5) node2 = Node(10)

node3 = Node(15)

node1.next = node2

node2.next = node3 ```

3. **Traverse the Linked

List:** ```python current =

node1 while current:

print(current.data)

current = current.next

```

This basic structure can be extended for different types of linked lists and implementations.

3-What do you mean by link list ? Write an


algorithm to insert and delete anode in singly
linked list?
**Linked List:**

A linked list is a linear data structure in which elements are stored in nodes, and each node points to
the next node in the sequence. Each node contains data and a reference (link or pointer) to the next
node. Linked lists allow dynamic memory allocation and efficient insertion and deletion operations.

**Algorithm to Insert a Node in a Singly Linked List:**

```plaintext

Algorithm InsertNode(list, data, position):


1. Create a new node with the given data.

2. If the list is empty or the position is 0:

a. Set the new node's next to the current head of the list.

b. Update the list head to the new node.

3. Else:

a. Traverse the list to the node at position - 1.

b. Set the new node's next to the next node of the current position.

c. Set the next node of the current position to the new node.

Example:

InsertNode(list: 5 -> 10 -> 15, data: 8, position: 2)

Result: 5 -> 8 -> 10 -> 15

```

**Algorithm to Delete a Node in a Singly Linked List:**

```plaintext

Algorithm DeleteNode(list, position):

1. If the list is empty or the position is 0:

a. Return an error (cannot delete).

2. If the position is 0:

a. Set the list head to the next node of the current head.

3. Else:

a. Traverse the list to the node at position - 1.

b. If the next node is null, return an error.

c. Set the next node of the current position to the next node of the next node.

Example:

DeleteNode(list: 5 -> 8 -> 10 -> 15, position: 2)

Result: 5 -> 10 -> 15

```
These algorithms assume a 0-based index for the position of the node in the linked list. Adjustments
may be needed based on the specific indexing convention used.

4-What do you mean by searching? Write a c


program for linear search and binary search . Write
their time complexing
**Searching:**

Searching is the process of finding a particular item or value in a collection of data. It involves
systematically examining each element in the collection until the desired item is found or
determining that it is not present.

**C Program for Linear Search:**

```c

#include <stdio.h>

int linearSearch(int arr[], int n, int target) { for (int i =

0; i < n; i++) { if (arr[i] == target) { return i; //

Return the index if the target is found

return -1; // Return -1 if the target is not found

int main() { int arr[] = {1, 2, 3, 4, 5};

int target = 3; int size = sizeof(arr) /

sizeof(arr[0]);

int result = linearSearch(arr, size, target);

if (result != -1) { printf("Element %d found at index

%d\n", target, result);


} else {

printf("Element %d not found in the array\n", target);

return 0;

```

**C Program for Binary Search:**

```c

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int target) {

while (low <= high) { int mid = low + (high - low) /

2;

if (arr[mid] == target) { return mid; // Return

the index if the target is found

if (arr[mid] < target) {

low = mid + 1; } else {

high = mid - 1;

return -1; // Return -1 if the target is not found

int main() { int arr[] = {1, 2, 3, 4, 5};

int target = 3; int size = sizeof(arr) /

sizeof(arr[0]);
int result = binarySearch(arr, 0, size - 1, target);

if (result != -1) { printf("Element %d found at index

%d\n", target, result);

} else {

printf("Element %d not found in the array\n", target);

return 0;

```

**Time Complexity:**

- Linear Search: O(n) - Linear time complexity because, in the worst case, the algorithm may
need to check each element in the collection.

- Binary Search: O(log n) - Logarithmic time complexity as it divides the search space in half
with each comparison in a sorted collection.

5-Define
1 graph
2 weighted graph
3 directed graph
4 undirected graph
5 indegree and out degree of a graph
6 adjacency matrix
1. **Graph:**

- A graph is a collection of nodes (vertices) and edges that connect pairs of nodes. It is a
fundamental data structure in computer science used to represent relationships between entities.

2. **Weighted Graph:**
- A weighted graph is a graph in which each edge is assigned a numerical value or weight. These
weights often represent distances, costs, or some other measure associated with the connection
between the nodes.

3. **Directed Graph:**

- A directed graph (or digraph) is a graph where edges have a direction, indicating a one-way
connection between nodes. Each edge has a starting node (tail) and an ending node (head), forming
an ordered pair.

4. **Undirected Graph:**

- An undirected graph is a graph in which edges have no direction. The connection between nodes
is bidirectional, and there is no distinction between the starting and ending nodes of an edge.

5. **Indegree and Outdegree of a Graph:**

- **Indegree:** For a directed graph, the indegree of a node is the number of incoming edges.
It represents how many edges point towards a particular node.

- **Outdegree:** For a directed graph, the outdegree of a node is the number of outgoing
edges. It represents how many edges originate from a particular node.

6. **Adjacency Matrix:**

- An adjacency matrix is a 2D array where each element (i, j) represents a connection between node
i and node j. In a binary adjacency matrix, the presence of an edge is indicated by a 1, and its
absence by a 0. For weighted graphs, the matrix contains the weight of the edge or a special value
(e.g., infinity) if there is no edge.

Example of an undirected graph with three nodes (A, B, C) and two edges (A-B, B-C):

```

A B C

A0 1 0

B1 0 1

C0 1 0

```

These concepts are fundamental in graph theory and are used in various applications such as
network design, routing algorithms, social network analysis, and more.
6-What is sorting? What do you mean by internal
and external sorting? List the different types of
sorting technique write their times complexity
**Sorting:**

Sorting is the process of arranging elements in a specific order, often in ascending or descending
numerical or lexicographical order. It is a fundamental operation in computer science and is used to
organize data for efficient searching and retrieval.

**Internal Sorting:**

Internal sorting involves sorting data that fits entirely into the computer's main memory (RAM). The
entire dataset is loaded into memory, and sorting operations are performed there.

**External Sorting:**

External sorting is used when the dataset is too large to fit into the computer's main memory. It
involves using external storage, such as hard drives, to handle parts of the dataset that cannot be
accommodated in RAM. External sorting is more complex due to the need for efficient management
of data in external storage.

**Types of Sorting Techniques and Their Time Complexity:**

1. **Bubble Sort:**

- Time Complexity: Best Case - O(n), Average Case - O(n^2), Worst Case - O(n^2)

- Simple but inefficient. It repeatedly steps through the list, compares adjacent elements, and swaps
them if they are in the wrong order.

2. **Insertion Sort:**

- Time Complexity: Best Case - O(n), Average Case - O(n^2), Worst Case - O(n^2)

- Builds the final sorted array one element at a time. Efficient for small datasets or nearly sorted data.

3. **Selection Sort:**

- Time Complexity: Best Case - O(n^2), Average Case - O(n^2), Worst Case - O(n^2)

- Divides the input into a sorted and an unsorted region. Repeatedly selects the minimum element
from the unsorted region and swaps it with the first element of the unsorted region.
4. **Merge Sort:**

- Time Complexity: Best Case - O(n log n), Average Case - O(n log n), Worst Case - O(n log n)

- Uses a divide-and-conquer strategy. Divides the array into two halves, recursively sorts them, and
then merges the sorted halves.

5. **Quick Sort:**

- Time Complexity: Best Case - O(n log n), Average Case - O(n log n), Worst Case - O(n^2)

- Also uses a divide-and-conquer strategy. Selects a "pivot" element and partitions the other
elements into two sub-arrays according to whether they are less than or greater than the pivot.

6. **Heap Sort:**

- Time Complexity: Best Case - O(n log n), Average Case - O(n log n), Worst Case - O(n log n)

- Builds a binary heap and repeatedly extracts the maximum element, placing it in the sorted portion
of the array.

These time complexities provide an indication of the efficiency of each sorting algorithm, and the
choice of which algorithm to use depends on factors such as the size and nature of the dataset.

Define an AVL tree obtain and AVL tree by inserting one integer at a time in the following sequence
50,55,60,15,10,40,20,45,30,47,70,80

**AVL Tree:**

An AVL tree (Adelson-Velsky and Landis tree) is a self-balancing binary search tree. In an AVL tree, the
heights of the two child subtrees of any node differ by at most one, ensuring that the tree remains
balanced after insertions and deletions.

**AVL Tree Insertion:**

To obtain an AVL tree, we'll insert the integers one at a time while maintaining the balance property.
Here are the steps for inserting the sequence [50, 55, 60, 15, 10, 40, 20, 45, 30, 47, 70, 80]:

1. **Insert 50:**

- Tree: `50`

2. **Insert 55:**
- Tree:

```

50

55

```

3. **Insert 60:**

- Tree:

```

50

55

60

```

4. **Insert 15:**

- Tree:

```

50

/\

15 55

60

```

5. **Insert 10:**

- Tree:

```

50
/\

15 55

/ \

10 60

```

6. **Insert 40:**

- Tree:

```

50

/\

15 55

/\ \

10 40 60

```

7. **Insert 20:**

- Tree:

```

50

/\

15 55

/\ \

10 40 60

20

```

8. **Insert 45:**

- Tree:

```
50

/\

15 55

/\ \

10 40 60

/\

20 45

```

9. **Insert 30:**

- Tree:

```

50

/\

15 55

/\ \

10 40 60

/\

20 45

30

```

10. **Insert 47:**

- Tree:

```

50

/\

15 55

/\ \

10 40 60
/\

20 45

/\

30 47

```

11. **Insert 70:**

- Tree:

```

50

/\

15 55

/\ \

10 40 60

/\ \

20 45 70

/\

30 47

```

12. **Insert 80:**

- Tree:

```

50

/\

15 60

/\ \

10 40 70

/\ \

20 45 80

/\
30 47

```

The resulting tree is now an AVL tree, maintaining the balance property. Each node's balance factor
(the height difference between its left and right subtrees) is either -1, 0, or 1.

7-Define binary search tree. Draw the binary search


tree that is created if the following no.are intrested
in the tree in the given order.
Kavita,helan,reena,sonam,amir,ranbir,salman,abhis
hek
**Binary Search Tree (BST):**

A binary search tree is a binary tree data structure where each node has at most two child nodes,
usually referred to as the left child and the right child. The key property of a BST is that the key (or
value) of each node must be greater than or equal to all the nodes in its left subtree and less than or
equal to all the nodes in its right subtree.

**BST for the Given Names:**

Let's create a binary search tree with the names Kavita, Helan, Reena, Sonam, Amir, Ranbir, Salman,
and Abhishek in the given order:

1. Insert Kavita:

```

Kavita

```

2. Insert Helan:

```

Kavita

Helan

```
3. Insert Reena:

```

Kavita

Helan

Reena

```

4. Insert Sonam:

```

Kavita

Helan

Reena

Sonam

```

5. Insert Amir:

```

Kavita

Helan

Reena

Sonam

Amir
```

6. Insert Ranbir:

```

Kavita

Helan

Reena

Sonam

Amir

Ranbir

```

7. Insert Salman:

```

Kavita

Helan

Reena

Sonam

Amir

Ranbir

Salman
```

8. Insert Abhishek:

```

Kavita

Helan

Reena

Sonam

Amir

Ranbir

Salman

Abhishek

```

The resulting binary search tree satisfies the BST property, where each node's key is greater than or
equal to all nodes in its left subtree and less than or equal to all nodes in its right subtree.

8-Distinguished between
(a) iteration and recursion
(b) datatype and data structure
(c) time complexity and space complexity
(d) binary tree and binary search tree
(a) **Iteration and Recursion:**
- **Iteration:** It is a process of repeatedly executing a set of instructions or statements in a
sequence. It uses loops to repeat a block of code until a certain condition is met.

- **Recursion:** It is a programming concept where a function calls itself in its own definition.
It breaks a problem into smaller sub-problems and solves them, typically with a base case to stop the
recursion.

(b) **Datatype and Data Structure:**

- **Datatype:** It is a classification that specifies which type of data a variable can hold.
Examples include integers, floating-point numbers, characters, etc.

- **Data Structure:** It is a way of organizing and storing data to perform operations


efficiently. Examples include arrays, linked lists, stacks, and queues.

(c) **Time Complexity and Space Complexity:**

- **Time Complexity:** It measures the amount of time an algorithm takes concerning the
size of the input. It is often expressed using Big O notation.

- **Space Complexity:** It measures the amount of memory an algorithm uses concerning


the size of the input. It is also expressed using Big O notation.

(d) **Binary Tree and Binary Search Tree:**

- **Binary Tree:** It is a hierarchical data structure in which each node has at most two
children, referred to as the left child and the right child. There are no specific ordering rules for the
nodes.

- **Binary Search Tree (BST):** It is a specific type of binary tree where the key (or value) of
each node is greater than or equal to all the nodes in its left subtree and less than or equal to all the
nodes in its right subtree. It enables efficient searching, insertion, and deletion operations.

In summary:

(a) Iteration involves loops and repeated execution, while recursion involves a function calling itself.

(b) Datatype refers to the type of data a variable can hold, and data structure is a way of organizing
and storing data.

(c) Time complexity measures algorithmic efficiency in terms of time, and space complexity
measures memory usage.

(d) A binary tree is a general hierarchical structure, while a binary search tree imposes ordering rules
on the nodes for efficient searching.

What are two types of complexities ? Explain them .explain the concept of big 0 and big omegas and
thetha
**Two Types of Complexities:**

1. **Time Complexity:**

- **Definition:** Time complexity is a measure of the amount of time an algorithm takes to


complete as a function of the size of the input.

- **Objective:** It helps analyze how the execution time of an algorithm grows with the size
of the input.

- **Notation:** Represented using Big O notation (O), which provides an upper bound on the
growth rate.

2. **Space Complexity:**

- **Definition:** Space complexity is a measure of the amount of memory an algorithm uses


concerning the size of the input.

- **Objective:** It helps analyze how the memory requirements of an algorithm grow with
the size of the input.

- **Notation:** Also represented using Big O notation (O), which provides an upper bound on
the memory usage.

**Big O, Big Omega, and Theta:**

1. **Big O (O):**

- **Definition:** Big O notation represents an upper bound on the growth rate of an


algorithm. It gives the worst-case scenario for the time or space complexity.

- **Example:** If an algorithm has a time complexity of O(n), it means the execution time
grows linearly with the size of the input.

2. **Big Omega (Ω):**

- **Definition:** Big Omega notation represents a lower bound on the growth rate of an
algorithm. It gives the best-case scenario for the time or space complexity.

- **Example:** If an algorithm has a time complexity of Ω(n^2), it means the execution time
grows at least quadratically with the size of the input.

3. **Theta (Θ):**

- **Definition:** Theta notation represents both an upper and a lower bound on the growth
rate of an algorithm. It provides a tight bound, indicating the best and worst-case scenarios are
essentially the same.
- **Example:** If an algorithm has a time complexity of Θ(n), it means the execution time
grows linearly, and the best and worst cases have the same growth rate.

In summary, Big O provides an upper bound, Big Omega provides a lower bound, and Theta provides
a tight bound on the growth rate of algorithms. These notations are crucial for understanding and
comparing the efficiency of different algorithms.

9-What is queue? Why it is known as fifo? Write


an algorithm to insert and delete an element from a
simple queue

**Queue:**

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle, meaning that the
element that is inserted first is the one that comes out first. It's similar to a real-world queue or line
where the person who arrives first is served first.

**FIFO (First-In-First-Out):**

The term "FIFO" describes the order in which elements are processed in a queue. The element that
has been in the queue the longest is the first one to be removed.

**Queue Operations:**

- **Enqueue (Insert):** Adds an element to the end of the queue.

- **Dequeue (Delete):** Removes the element from the front of the queue.

**Algorithm to Insert (Enqueue) an Element into a Simple Queue:**

```plaintext

Algorithm Enqueue(queue, element):

1. Increment the rear pointer.

2. Add the element to the position pointed by the rear.

```

**Algorithm to Delete (Dequeue) an Element from a Simple Queue:**

```plaintext
Algorithm Dequeue(queue):

1. If the queue is empty (front > rear):

a. Print an error (underflow).

2. Otherwise:

a. Retrieve the element at the front.

b. Increment the front pointer.

```

**Example Implementation in Python:**

```python class SimpleQueue:

def __init__(self, capacity):

self.capacity = capacity

self.queue = [None] * capacity

self.front = self.rear = -1

def enqueue(self, element):

if self.rear == self.capacity - 1:

print("Queue Overflow")

else:

if self.front == -1: self.front = 0

self.rear += 1 self.queue[self.rear] =

element print(f"{element} enqueued to

the queue")

def dequeue(self):

if self.front == -1:

print("Queue Underflow")

return None else:

element = self.queue[self.front]

self.front += 1 return element

```
In this Python implementation, the `enqueue` method adds an element to the end of the queue, and
the `dequeue` method removes and returns the element from the front of the queue. The `front`
and `rear` pointers keep track of the position of the first and last elements in the queue, respectively.

10-Explain breadth first search transversal and


depth first search transversal of geaph using an
example
**Breadth-First Search (BFS) Traversal:**

BFS is a graph traversal algorithm that explores all the vertices of a graph level by level, visiting all the
neighbors of a vertex before moving on to the next level.

**Example:**

Consider the following undirected graph:

```

/\

B C

| |

D E

```

Starting at vertex A, the BFS traversal would be: A, B, C, D, E.

**Algorithm for BFS:**

1. Enqueue the starting vertex into a queue.

2. While the queue is not empty:

a. Dequeue a vertex from the queue and visit it.

b. Enqueue all unvisited neighbors of the visited vertex.


**Depth-First Search (DFS) Traversal:**

DFS is a graph traversal algorithm that explores as far as possible along each branch before
backtracking. It uses a stack or recursion to keep track of vertices to visit.

**Example:**

Using the same graph as above, starting at vertex A, the DFS traversal could be: A, B, D, E, C.

**Algorithm for DFS (Recursive):** 1.

Mark the current vertex as visited.

2. Visit the current vertex.

3. Recursively visit all unvisited neighbors of the current vertex.

**Algorithm for DFS (Stack-based):** 1.

Push the starting vertex onto a stack.

2. While the stack is not empty:

a. Pop a vertex from the stack and visit it.

b. Push all unvisited neighbors of the visited vertex onto the stack.

In the example graph, the DFS traversal starts at A, explores as far as possible along each branch
before backtracking. The order of visited vertices is A, B, D, E, C.

11-What is circular linked list? State the


advantages and disadvantages of circular link list
over doubly linked list and singly linked list. Also
write advantages of linked list over an array
**Circular Linked List:**

A circular linked list is a variation of a linked list in which the last node points back to the first node,
forming a circle. In other words, the next pointer of the last node is not NULL but points to the first
node.

**Advantages of Circular Linked List:**


1. **Efficient Operations:** Circular linked lists can be more efficient than singly linked lists for
certain operations since there is no distinct end, and operations can wrap around the list.

2. **Efficient Memory Utilization:** The last node points back to the first, saving memory
compared to a linear singly linked list.

3. **Implementation of Circular Buffers:** Circular linked lists are useful in implementing


circular buffers, which have applications in managing data streams.

**Disadvantages of Circular Linked List:**

1. **Complexity:** Operations can be slightly more complex due to the circular nature,
requiring careful handling to avoid infinite loops.

2. **Traversal Challenges:** Traversing a circular linked list requires additional care to avoid an
infinite loop if not implemented properly.

**Advantages of Circular Linked List over Singly/Doubly Linked List:**

1. **Efficient Operations:** Certain operations like rotation or cycling through elements can be
more efficient.

2. **Space Efficiency:** Circular linked lists can save memory compared to linear linked lists
since the last node points back to the first.

**Advantages of Linked List over an Array:**

1. **Dynamic Size:** Linked lists can dynamically resize, allowing efficient memory utilization
as compared to arrays with fixed sizes.

2. **Ease of Insertion and Deletion:** Insertion and deletion operations are more efficient in
linked lists, especially in the middle, compared to arrays.

3. **No Pre-allocation of Memory:** Linked lists allow adding elements without pre-allocating
memory, unlike arrays where a fixed size must be declared in advance.

4. **Ease of Implementation:** Linked lists are easier to implement and manage in certain
scenarios, such as when the size is unknown or subject to change.

Discuss following with reference to trees


1 height of the tree
2 complete binary tree
3 expression tree
4 sibling
5 full binary tree
**1. Height of the Tree:**

- **Definition:** The height of a tree is the length of the longest path from the root node to a leaf
node. It represents the depth of the deepest node in the tree.

- **Notation:** Typically denoted as h or height.

- **Usage:** It is a crucial parameter in analyzing the performance of various tree operations, as it


determines the time complexity for operations like insertion, deletion, and searching.

**2. Complete Binary Tree:**

- **Definition:** A binary tree is considered complete if all levels, except possibly the last, are
completely filled, and all nodes are as left as possible. In the last level, nodes are filled from left to
right without any gaps.

- **Properties:** Complete binary trees are efficiently stored in arrays, and the relationship between
the index of a node and its parent/children is well-defined.

- **Example:**

```

/\

2 3

/\/

4 56

```

**3. Expression Tree:**

- **Definition:** An expression tree is a binary tree where each leaf node represents an operand,
and each non-leaf node represents an operator. It is used to represent expressions in a tree form. -
**Usage:** Expression trees are employed in compilers to evaluate mathematical expressions
efficiently.

- **Example:**

```

/\

* 3
/\

2 5

```

**4. Sibling:**

- **Definition:** In a tree, nodes with the same parent are called siblings. Siblings share the same
parent node.

- **Usage:** Understanding the concept of siblings is essential in tree traversal and manipulation
algorithms.

- **Example:**

```

/\

2 3

/\

4 5

```

Nodes 2 and 3 are siblings, as are nodes 4 and 5.

**5. Full Binary Tree:**

- **Definition:** A full binary tree (also called a proper or plane binary tree) is a binary tree in which
every node has either 0 or 2 children, but never 1 child.

- **Properties:** In a full binary tree, the number of leaf nodes is either equal to or one more than
the number of nodes with two children.

- **Example:**

```

/\

2 3

/\

4 5

```
This is a full binary tree as each node has either 0 or 2 children.

Understanding these tree concepts is fundamental in various areas of computer science, including
data structures, algorithms, and compiler design.

12-Explain the various representations of graph


with explain in detail?
Graphs can be represented using various data structures, each offering different advantages and
trade-offs based on the types of operations to be performed. The main representations of a graph
are:

1. **Adjacency Matrix:**

- **Definition:** An adjacency matrix is a 2D array where the element at position (i, j) represents the
presence or absence of an edge between vertex i and vertex j. For an undirected graph, the matrix
is symmetric.

- **Space Complexity:** Takes O(V^2) space, where V is the number of vertices.

- **Pros:**

- Easy to implement and understand.

- Efficient for dense graphs.

- **Cons:**

- Inefficient for sparse graphs (large number of vertices but few edges).

- Takes more space compared to other representations for sparse graphs.

2. **Adjacency List:**

- **Definition:** An adjacency list is a collection of lists, where each list represents the neighbors of
a vertex. It's a more memory-efficient representation for sparse graphs.

- **Space Complexity:** Takes O(V + E) space, where V is the number of vertices and E is the number
of edges.

- **Pros:**

- Memory-efficient for sparse graphs.

- Efficient for traversing neighbors of a vertex.

- **Cons:**

- Not as efficient for dense graphs.

- Requires more memory per edge compared to adjacency matrix.


3. **Edge List:**

- **Definition:** An edge list is an array of tuples, where each tuple represents an edge by specifying
the two vertices it connects. Additionally, a weight can be included for weighted graphs.

- **Space Complexity:** Takes O(E) space, where E is the number of edges.

- **Pros:**

- Simple representation.

- Memory-efficient for sparse graphs.

- **Cons:**

- Inefficient for determining neighbors of a vertex.

- Requires linear search for checking edge existence.

4. **Incidence Matrix:**

- **Definition:** An incidence matrix is a 2D array where the rows represent vertices, columns
represent edges, and the entries indicate the incidence of vertices on edges.

- **Space Complexity:** Takes O(V * E) space, where V is the number of vertices and E is the number
of edges.

- **Pros:**

- Suitable for certain graph algorithms.

- **Cons:**

- Takes more space compared to other representations.

- Inefficient for traversing neighbors.

Choosing the right representation depends on the nature of the graph and the types of operations
that need to be performed efficiently. Adjacency lists are commonly used due to their efficiency for
most graph algorithms and their ability to handle sparse graphs well.

You might also like