Which of the following is a key reason why trees are used instead of arrays or linked lists for certain data problems?
Think about how data is organized in family trees or file folders.
Trees represent hierarchical relationships naturally, unlike arrays or linked lists which are linear. This makes trees ideal for data like file systems or organizational charts.
Consider a simple tree node class and connections below. What is the printed output?
class Node: def __init__(self, val): self.val = val self.children = [] root = Node(1) child1 = Node(2) child2 = Node(3) root.children.append(child1) root.children.append(child2) print(root.val) print([child.val for child in root.children])
Look at the order children are added to the root.
The root node has value 1. Children are added in order 2 then 3, so the list of children values is [2, 3].
Given the code below, what is the main reason this linked list structure fails to represent a hierarchy like a tree?
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)Think about how many 'next' pointers each node has.
Each node in a linked list points to only one next node, so it cannot branch into multiple children like a tree node can.
You want to represent a file system with folders and files. Which data structure is best and why?
Think about how folders contain subfolders and files.
File systems are hierarchical, with folders containing other folders or files. Trees represent this structure naturally.
What is the output of the code below that traverses a tree and a linked list?
class TreeNode: def __init__(self, val): self.val = val self.children = [] class ListNode: def __init__(self, val): self.val = val self.next = None # Build tree root = TreeNode(1) child1 = TreeNode(2) child2 = TreeNode(3) root.children.append(child1) root.children.append(child2) # Build linked list head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) # Traverse tree (only root and immediate children) tree_vals = [root.val] + [child.val for child in root.children] # Traverse linked list list_vals = [] current = head while current: list_vals.append(current.val) current = current.next print(tree_vals) print(list_vals)
Check the order children are added and how linked list is traversed.
The tree root has children 2 and 3 added in order, so tree_vals is [1, 2, 3]. The linked list is traversed from head to tail, so list_vals is [1, 2, 3].
