Question DSA-TREE-0015
HardWhat is the output of this code?
class Node:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
from collections import deque
q, out = deque([root]), []
while q:
level = []
for _ in range(len(q)):
n = q.popleft()
level.append(n.v)
for c in (n.l, n.r):
if c:
q.append(c)
out.append(level)
print(out)
- A.
[[1, 2, 3, 4, 5]]
- B.
[[1], [2], [3], [4], [5]]
- C.
[[1], [2, 3], [4, 5]]
- D.
[[4, 5], [2, 3], [1]]
Sign up free to see the answer and a step-by-step explanation.