Subhajit Das Data Structures and Algorithms
Subhajit Das Data Structures and Algorithms
1. What are the steps to convert a general tree into binary tree?
Converting a general tree into a binary tree involves a specific set of rules to rearrange the
nodes. Here are the steps to perform the conversion:
Root Node: The root of the binary tree is the same as the root of the general tree.
Left Child: The left child of a node in the binary tree is the leftmost child of that node in the
general tree.
Right Child: The right sibling of any node in the general tree becomes the right child of that
node in the binary tree.
Let’s consider a general tree with root node A, and its children B, C, and D, where B is the
leftmost child. In the binary tree:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.children = []
def convert_to_binary_tree(root):
if not root:
return None
return root
def print_binary_tree(root, depth=0):
if root is not None:
print_binary_tree(root.left, depth + 1)
print(' ' * 4 * depth + '->', root.value)
print_binary_tree(root.right, depth + 1)
# Example usage:
root = Node('A')
root.children.append(Node('B'))
root.children.append(Node('C'))
root.children.append(Node('D'))
Push: Adds an element to the top of the stack. If the stack is full, it results in an overflow
condition.
Pop: Removes the top element from the stack. If the stack is empty when attempting to pop, it
results in an underflow condition.
Top or Peek: Returns the top element of the stack without removing it from the stack.
isEmpty: Checks if the stack is empty. It returns true if the stack is empty, otherwise false.
isFull: Checks if the stack has reached its maximum capacity. It returns true if the stack is full,
otherwise false.
Size: Returns the number of elements present in the stack.
These operations allow you to manipulate the data within the stack, adhering to its LIFO
nature. For example, in programming, stacks are used for function call management,
expression evaluation, and more.
# Example usage:
array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
largest, smallest = find_largest_smallest(array)
print("Largest:", largest)
print("Smallest:", smallest)
This code will output the largest and smallest numbers in the given array. The time complexity
of this algorithm is O(n), where n is the number of elements in the array, because it requires a
single pass through the array.