Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def build(xs, i=0):
if i >= len(xs) or xs[i] is None: return None
return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
from collections import deque
def levels(root):
out, q = [], deque([root])
while q:
lvl = []
for _ in range(len(q)):
n = q.popleft(); lvl.append(n.v)
if n.l: q.append(n.l)
if n.r: q.append(n.r)
out.append(lvl)
return out
print(levels(build([3, 9, 20, None, None, 15, 7])))What is printed?- A. [[3], [9, 20, 15, 7]]
- B. [[3], [20, 9], [15, 7]]
- C. [[3], [9, 20], [15, 7]]
- D. [3, 9, 20, 15, 7]
Correct answer: C. [[3], [9, 20], [15, 7]]
BFS with a queue; freezing len(q) at the start of each round separates the levels. O(n) time, O(width) space.
More Coding Interview Problems questions
- Problem: Return the right-side view of a tree (the last node of each level). Trees are built by build(xs): a level-order list where index…
- Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. Trees are built by…
- Problem: Find the lowest common ancestor of two keys in a BST. Trees are built by build(xs): a level-order list where index i has children…
- Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2…
- Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. Trees are built by build(xs): a…
- Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be…