Consider this simple tree represented as nested lists. What will be the output of the preorder traversal?
def preorder(tree): if not tree: return [] root, children = tree[0], tree[1:] result = [root] for child in children: result.extend(preorder(child)) return result tree = ['A', ['B', ['D'], ['E']], ['C', ['F']]] print(preorder(tree))
Preorder means visit root first, then children from left to right.
The preorder traversal visits the root node first, then recursively visits each child subtree from left to right. So the output is ['A', 'B', 'D', 'E', 'C', 'F'].
Which data structure is best to represent a company's organizational chart where each employee can have multiple subordinates?
Think about parent-child relationships and multiple children per node.
A tree structure is best for hierarchical data like an organizational chart because it can represent parent-child relationships with multiple children per node naturally.
This code tries to represent a hierarchy using a singly linked list. What is the main problem?
class Node: def __init__(self, value): self.value = value self.next = None # Trying to represent a manager with two subordinates manager = Node('Manager') sub1 = Node('Subordinate1') sub2 = Node('Subordinate2') manager.next = sub1 sub1.next = sub2 # Print chain current = manager while current: print(current.value) current = current.next
Think about how many children a node can have in a singly linked list.
A singly linked list allows only one next node, so it cannot represent multiple children from one parent node, which is needed for hierarchy.
What is the output of this code that flattens a tree into an array using depth-first search?
def flatten(tree): result = [] def dfs(node): if not node: return result.append(node['value']) for child in node.get('children', []): dfs(child) dfs(tree) return result tree = { 'value': 1, 'children': [ {'value': 2, 'children': [{'value': 4}, {'value': 5}]}, {'value': 3} ] } print(flatten(tree))
Depth-first search visits node before children, left to right.
The DFS visits root 1, then child 2 and its children 4 and 5, then child 3, producing [1, 2, 4, 5, 3].
Which reason best explains why trees are preferred over arrays when representing hierarchical data?
Think about how hierarchy and branching are represented.
Trees explicitly represent parent-child relationships and allow nodes to have multiple children, which arrays cannot do naturally.
