DATA STRUCTURE (What Is What)
DATA STRUCTURE (What Is What)
7) What is a queue?
A queue is a data structure that can simulate a list or stream of data. In this
structure, new elements are inserted at one end, and existing elements are
removed from the other end.
29) What is the minimum number of nodes that a binary tree can have?
A binary tree can have a minimum of zero nodes, which occurs when the nodes
have NULL values. Furthermore, a binary tree can also have 1 or 2 nodes.
51) Which data structures are used for BFS and DFS of a graph?
BFS (Breadth-First Search) and DFS (Depth-First Search) are graph traversal
algorithms. BFS visits vertices in a breadth-wise fashion, exploring all vertices at
the same level before moving to the next level, using a queue to maintain the
order. DFS explores vertices in a depth-wise manner, going as deep as possible
before backtracking, utilizing a stack to track visited vertices. The choice between
BFS and DFS depends on the problem and graph characteristics, with BFS
suitable for shortest path and uniform edge weight scenarios, while DFS is useful
for exploring deeply and searching for paths.
To implement a stack using a queue, create two instances of the queue: the "main
Queue" and "helper Queue." For pushing an element, enqueue it into the main
Queue and if there are elements in the helper Queue, dequeue them and enqueue
into the main Queue. Then swap the names of the main Queue and helper Queue.
To pop an element, dequeue from the main Queue. To access the top element,
return the front element of the main Queue without dequeuing it. This approach
ensures that the most recently pushed element is always at the front of the main
Queue, simulating the behaviour of a stack.
To implement a queue using a stack, create two stacks: the "mainStack" and
"helperStack." For enqueueing an element, push it onto the mainStack. To
dequeue an element, if both stacks are empty, indicate an empty queue error. If
the helperStack is empty, transfer all elements from the mainStack to the
helperStack by popping from mainStack and pushing into helperStack until
mainStack is empty. Then, pop and return the top element from the helperStack.
This approach ensures that the oldest enqueued element is at the top of the
helperStack, simulating the behavior of a queue. Enqueueing takes O(1) time
complexity, and dequeueing takes amortized O(1) time complexity.