Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Tree itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)A rooted tree gives each non-root node one parent and one route from the root. Choose preorder to act before children, postorder to combine completed subtrees, or breadth order to group depth; a binary tree is only one specialization.
1 practice exercise2 interview problems
Recognize it when Input is an acyclic hierarchy with one parent per non-root node.
Checking your account…
A rooted tree is a hierarchy with one root, one parent for every other node, and a unique path from the root to each node. Removing any parent-child edge separates one subtree. This makes subtree results independent and composable, even when nodes have more than two children.
Define a recursive helper over one node’s complete subtree. Preorder performs node work before its children; postorder waits until every child result is ready. A tree needs no visited set when input already provides directed child lists and guarantees acyclicity.
The Python recursion model(opens in a new tab) still limits safe call depth, so an explicit stack is appropriate for a long chain.
Traversal order is part of the algorithm, not presentation. Preorder is useful for propagation and serialization; postorder supports aggregation and deletion; breadth order groups equal depth. For ordered children, preserve their stated order when pushing onto a LIFO stack.
def traversal_orders(children, root):
preorder = []
postorder = []
def visit(node):
preorder.append(node)
for child in children[node]:
visit(child)
postorder.append(node)
visit(root)
return preorder, postorderImplement traversal_orders(children, root). Return preorder and postorder lists while preserving each node's authored child order.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def traversal_orders(children, root):
preorder = []
postorder = []
def visit(node):
preorder.append(node)
for child in children[node]:
visit(child)
postorder.append(node)
visit(root)
return preorder, postorderThe existing recursive Lab visits root 0 with children 1 and 2. Entry and return happen at different times even for the same node: the root enters first but returns last after both independent child subtrees complete.
print(traversal_orders([[1, 2], [], []], 0)) followed by print(traversal_orders([[]], 0))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | preorder.append(node) |
node = 0; preorder = [0]; postorder = [] |
Entry records the parent before any child work. |
| 2 | visit(child); preorder.append(node) |
child = 1; preorder = [0, 1] |
Authored child order selects node 1 first. |
| 3 | postorder.append(node) |
node = 1; postorder = [1] |
The leaf has no pending children and can complete immediately. |
| 4 | visit(child); preorder.append(node); postorder.append(node) |
child = 2; preorder = [0, 1, 2]; postorder = [1, 2] |
The second child completes before the parent’s return. |
| 5 | postorder.append(node); return preorder, postorder |
node = 0; result = ([0, 1, 2], [1, 2, 0]) |
The parent completes only after every authored child. |
| Output | |
|---|---|
| 1 | ([0, 1, 2], [1, 2, 0]) |
| 2 | ([0], [0]) |
Preorder can carry ancestor decisions down; postorder can consume completed child results. This trace is an arbitrary-child tree contract, so the same loop must also handle a third or later child.
An undirected acyclic edge list becomes a rooted tree after choosing a root. Traverse once, skip the parent edge, and assign each child’s parent and depth. The parent check replaces a general visited set because a tree has no alternate route back to an earlier node.
def parent_and_depth(node_count, edges, root):
adjacency = [[] for _ in range(node_count)]
for left, right in edges:
adjacency[left].append(right)
adjacency[right].append(left)
parent = [-2] * node_count
depth = [-1] * node_count
parent[root] = -1
depth[root] = 0
stack = [root]
while stack:
node = stack.pop()
for neighbor in adjacency[node]:
if neighbor == parent[node]:
continue
parent[neighbor] = node
depth[neighbor] = depth[node] + 1
stack.append(neighbor)
return parent, depthImplement parent_and_depth(node_count, edges, root). Return parent and depth arrays after rooting the undirected tree; the root parent is -1.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def parent_and_depth(node_count, edges, root):
adjacency = [[] for _ in range(node_count)]
for left, right in edges:
adjacency[left].append(right)
adjacency[right].append(left)
parent = [-2] * node_count
depth = [-1] * node_count
parent[root] = -1
depth[root] = 0
stack = [root]
while stack:
node = stack.pop()
for neighbor in adjacency[node]:
if neighbor == parent[node]:
continue
parent[neighbor] = node
depth[neighbor] = depth[node] + 1
stack.append(neighbor)
return parent, depthUse node objects when recursive structure is supplied directly, child lists for arbitrary branching, an adjacency list for undirected edges, and parent arrays for ancestor/depth preprocessing. A binary tree specializes child count; a BST adds ordering. A graph is required when cycles or multiple paths are allowed.
State the root, representation, and return contract for one subtree. Name why the chosen traversal order matches when information becomes available. Give O(n) time because each node/edge is processed once and O(h) recursive space or O(w) breadth frontier space.
Profile a Binary Tree(opens in a new tab) is one binary specialization. Binary Tree Level Order(opens in a new tab) tests whether breadth grouping is chosen instead of generic recursion.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Tree itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Preorder and postorder traversal | O(n) | O(n) | n reachable nodes; stores two output lists and up to height h recursive frames. Python recursion depth remains bounded. |
| Build rooted parent/depth arrays | O(n) | O(n) | Connected valid undirected tree has n-1 edges; adjacency, arrays and frontier use linear storage. |
O(n + h) for preorder and postorder traversal; O(n) for build rooted parent/depth arrays.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Taking only the first two child entries drops valid later subtrees.
Prevent it: Iterate every authored child unless the input contract is explicitly binary.
selected = children[node][:2]selected = list(children[node])Where you will hit this: Profile a Binary Tree(opens in a new tab)
An undirected neighbor list includes the parent. Re-enqueuing it reverses direction and can make parent/depth traversal cycle.
Prevent it: Exclude the current node's parent under a valid tree contract.
next_nodes = list(adjacency[node])next_nodes = [neighbor for neighbor in adjacency[node] if neighbor != parent[node]]Where you will hit this: Profile a Binary Tree(opens in a new tab)
A parent-first list is preorder. A subtree aggregate cannot be final until its child results are available.
Prevent it: Combine completed child postorders before appending the parent.
postorder = [node]
for child_result in child_postorders:
postorder.extend(child_result)postorder = []
for child_result in child_postorders:
postorder.extend(child_result)
postorder.append(node)Where you will hit this: Binary Tree Level Order(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27