Count median in binary tree
Last updated: August 18, 2025
Quick Overview
Given a binary tree, write a function to calculate the median value of all the nodes in the tree. The median is defined as the middle value when the values are sorted; if there is an even number of values, return the average of the two middle values. Your function should take the root node of the binary tree as input and return the median as a float.
TikTok
August 18, 202574
15
3,811 solved
Given a binary tree, write a function to calculate the median value of all the nodes in the tree. The median is defined as the middle value when the values are sorted; if there is an even number of values, return the average of the two middle values. Your function should take the root node of the binary tree as input and return the median as a float.
TikTok uses this problem in the Phone Screen to evaluate your algorithmic thinking. They expect you to discuss multiple approaches, analyze trade-offs between them, and implement the optimal solution with clean, readable code.
What the Interviewer Expects
- Recognize the underlying problem pattern (sliding window, two pointers, BFS/DFS, etc.)
- Discuss multiple approaches and trade-offs before coding
- Implement an optimal solution with clean, production-quality code
- Handle all edge cases including boundary conditions and invalid input
- Optimize both time and space complexity with clear justification
- Test your solution systematically with well-chosen examples
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
- Can you solve this iteratively instead of recursively (or vice versa)?
- How would you test this solution thoroughly?
- What is the worst-case input for your solution?
- How would you parallelize this solution?
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
To find the median in a binary tree, we need to collect all the node values and sort them. The median is the middle value of the sorted list. If the list has an odd number of elements, the median is t...
Approach
- Traverse the Tree: Use a DFS approach to visit each node in the binary tree and collect their values. This can be done using a recursive function that adds each node's value to a list.
- **S...