Binary Tree Preorder Traversal
EasyTreesdfs
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given the root of a binary tree, return a list of its node values in **preorder**: visit a node, then its entire left subtree, then its entire right subtree.
An empty tree returns [].
The recursive version is short; as a follow-up, produce the same order iteratively with an explicit stack.
Examples
Input: root = [1,null,2,3]
Output: [1,2,3]
Visit 1, it has no left child, then its right child 2, then 2's left child 3.
Input: root = []
Output: []
There are no nodes to visit.
Input: root = [1,2,3,4,5]
Output: [1,2,4,5,3]
The whole left subtree (2, 4, 5) is listed before the right child 3.
Constraints
- 0 <= number of nodes <= 100
- -100 <= Node.val <= 100
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.