🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Tree Traversals: all 13 questions

Quiz: Tree Traversals · Question 9 of 13

What does this print? (code)

What does this print?

class Node:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

root = Node(1, Node(2, Node(4), Node(5)), Node(3))
def pre(n):
    return [n.val] + pre(n.left) + pre(n.right) if n else []
def ino(n):
    return ino(n.left) + [n.val] + ino(n.right) if n else []
print(pre(root), ino(root))
  1. A.[1, 2, 3, 4, 5] [4, 2, 5, 1, 3]
  2. B.[1, 2, 4, 5, 3] [4, 2, 5, 1, 3]
  3. C.[1, 2, 4, 5, 3] [4, 5, 2, 3, 1]
  4. D.[4, 2, 5, 1, 3] [1, 2, 4, 5, 3]
Answer & explanation

Correct answer: [1, 2, 4, 5, 3] [4, 2, 5, 1, 3]

Preorder visits the node first (root, left subtree, right subtree); inorder visits the left subtree, then the node, then the right.

Can you get the rest right without peeking?

Take the timed Quiz: Tree Traversals quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →