Dsa
Trees
Warm-up
Preorder Traversal
Implement a function that performs a preorder traversal of a binary tree and returns the values in the order they were visited.
Input format:
The first line contains an integer N, the number of nodes in the tree.
The next N lines contain three integers: the node value, the left child value, and the right child value, where -1 indicates that the child does not exist.
Output format:
Output a single line of space-separated integers representing the values in preorder.
Example:
Input:
4
1 2 3
2 -1 4
3 -1 -1
4 -1 -1
Output:
1 2 4 3
Key concepts
treestraversalpreorder
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now