DFS on binary tree
Last updated: November 20, 2025
Quick Overview
Implement a depth-first search (DFS) algorithm to traverse a binary tree. Given the root node of a binary tree, return the values of the nodes in the order they are visited during the DFS traversal. The output should be a list of node values.
Figma
November 20, 20252
1
4,719 solved
Implement a depth-first search (DFS) algorithm to traverse a binary tree. Given the root node of a binary tree, return the values of the nodes in the order they are visited during the DFS traversal. The output should be a list of node values.
Coding interviews at Figma focus on problem-solving approach as much as the final solution. The interviewer wants to see you break down the problem, consider edge cases, and optimize iteratively. Communication throughout the process is key.
What the Interviewer Expects
- Identify the correct data structure and algorithm for the problem
- Write clean, bug-free code with proper variable naming
- Analyze time and space complexity correctly
- Handle basic edge cases (empty input, single element)
- Communicate your thought process while coding
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What is the worst-case input for your solution?
- What if the input doesn't fit in memory?
- How would you test this solution thoroughly?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem requires us to perform a depth-first search (DFS) on a binary tree, which is a common graph traversal technique. In this case, DFS can be implemented using recursion or an explicit stack. ...
Approach
We will use a recursive DFS approach. The steps are as follows:
- Base Case: If the current node is NULL, we return immediately since there is nothing to process.
- Process the Current Node...