Question DSA-TREE-0006
EasyWhat 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))
def pre(n):
return [] if not n else [n.v] + pre(n.l) + pre(n.r)
print(*pre(root))
- A.
4 5 2 3 1
- B.
4 2 5 1 3
- C.
Show answer and explanation
Answer: D
Preorder visits the root, then the left subtree, then the right: 1, 2, 4, 5, 3.