DATA STRUCTURE UNIT III
DATA STRUCTURE UNIT III
3.BFS
ANS: Breadth First Search (BFS) is a fundamental graph traversal algorithm. It
begins with a node, then first traverses all its adjacent. Once all adjacent are
visited, then their adjacent are traversed. This is different from DFS in a way
that closest vertices are visited before others.
from collections import deque
def bfs(graph, root):
visited = set()
queue = deque([root])
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
def preorder_traversal(root):
if root:
print(root.value, end=' ') # Visit the root node
preorder_traversal(root.left) # Traverse the left subtree
preorder_traversal(root.right) # Traverse the right subtree
def prefix_notation(root):
if root:
print(root.value, end=' ') # Print the operator
prefix_notation(root.left) # Print the left operand
prefix_notation(root.right) # Print the right operand
8.recursive function
Ans: Recursive functions are a fundamental concept in programming, and
they can be very powerful when used correctly.
A recursive function is a function that calls itself in its own definition. This
allows the function to repeat its behavior until it reaches a base case that
stops the recursion.
Here is an example of a recursive function in Python that calculates the
factorial of a given integer:
1. The function takes an integer n as input.
2. The base case is when n is 0, in which case the function returns 1 (since
the factorial of 0 is 1).
3. If n is not 0, the function calls itself with n-1 as input, and multiplies
the result by n. This is the recursive step.
4. The function will continue to call itself until it reaches the base case, at
which point it will start returning values back up the call stack.
5. The final result is the product of all the integers from n down to 1,
which is the definition of the factorial.
9.Inorder search
Ans: Inorder search is a tree traversal algorithm that visits the nodes of a
binary search tree in ascending order. It is commonly used to search for a
specific value in a binary search tree.