PPractick

DSA interview question

Binary Tree Preorder Traversal

Easy · Data structures · Topics: tree, dfs, recursion

The problem

A file-explorer widget shows a folder tree, and its "export as outline" feature writes each folder before its contents: the folder itself, then everything in its first child, then everything in its second child. For a binary tree that's preorder: root, left subtree, right subtree. Recursion expresses it almost word for word, since visiting a subtree is the same problem on a smaller tree.

Example: [1, null, 2, 3] (1 has right child 2, and 2 has left child 3) → [1, 2, 3].

Function signature

vector<int> preorderTraversal(TreeNode* root);

Test cases

Input (level order)OutputExplanation
[1, null, 2, 3][1, 2, 3]
[1, 2, 3, 4, 5, null, 8, null, null, 6, 7, 9][1, 2, 4, 5, 6, 7, 3, 8, 9]
[][]Empty tree
[1][1]
[5, 4, 6][5, 4, 6]

(Confirm: the input uses LeetCode's level-order format with null for missing children; values may repeat.)

How interviewers phrase it

Clarifying questions to ask

  1. Recursive or iterative? (Recursive first; the iterative version is a common follow-up.)
  2. Can the tree be empty? (Yes.)
  3. How deep can it be? (Up to 100 nodes on LeetCode, so recursion depth is fine. Very deep trees need an explicit stack.)

Follow-ups to expect

  1. "What makes it preorder?"
  2. "Iterative version?"
  3. "O(1) extra space?"
  4. "Where is preorder used?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in