Program 3 : A book consists of chapters, chapters consist of sections and sections consist of
subsections. Construct a tree and print the nodes. Find the time and space requirements of your
method.
class Node:
def __init__(self, label=""):
self.label = label
self.children = []
class GT:
def __init__(self):
self.root = None
def create(self):
self.root = Node(input("Name of the book: "))
ch_count = int(input("Number of chapters: "))
for i in range(ch_count):
chapter = Node(input(f"Name of chapter {i+1}: "))
self.root.children.append(chapter)
sec_count = int(input("Number of sections: "))
for j in range(sec_count):
section = Node(input(f"Name of section {i+1}-{j+1}: "))
chapter.children.append(section)
sub_sec_count = int(input("Number of sub-sections: "))
for k in range(sub_sec_count):
sub_section = Node(input(f"Name of sub-section {i+1}-{j+1}-{k+1}: "))
section.children.append(sub_section)
def display(self, node, indent=""):
if node:
print(f"{indent}{node.label}")
for child in node.children:
self.display(child, indent + "\t")
g = GT()
while True:
print("--- MAIN MENU ---")
print("1 -> Add book info")
print("2 -> Display info")
print("3 -> Exit")
choice = int(input("Choose an option (1-3): "))
if choice == 1:
g.create()
elif choice == 2:
print("\nBook Information:")
g.display(g.root)
elif choice == 3:
print("\n// END OF CODE\n")
break
else:
print("Please choose a valid option (1-3).")
OUTPUT WILL BE -
--- MAIN MENU ---
1 -> Add book info
2 -> Display info
3 -> Exit
Choose an option (1-3): 1
Name of the book: DSF
Number of chapters: 1
Name of chapter 1: HASHING
Number of sections: 2
Name of section 1-1: HASH TABLE
Number of sub-sections: 2
Name of sub-section 1-1-1: HASH FUNCTION
Name of sub-section 1-1-2: HASH OPERATION
Name of section 1-2: CHAINING
Number of sub-sections: 2
Name of sub-section 1-2-1: CHAINING WITH REPLACEMENT
Name of sub-section 1-2-2: CHAINING WITHOUT REPLACEMENT
--- MAIN MENU ---
1 -> Add book info
2 -> Display info
3 -> Exit
Choose an option (1-3): 2
Book Information:
DSF
HASHING
HASH TABLE
HASH FUNCTION
HASH OPERATION
CHAINING
CHAINING WITH REPLACEMENT
CHAINING WITHOUT REPLACEMENT
--- MAIN MENU ---
1 -> Add book info
2 -> Display info
3 -> Exit
Choose an option (1-3): 3
// END OF CODE