Find longest subsequence in binary tree
Last updated: September 12, 2025
Quick Overview
Given a binary tree, write a function to find the longest subsequence of nodes such that each node in the subsequence is an ancestor of the next node. The function should return the length of this longest subsequence. The input will be the root node of the binary tree, and the output should be an integer representing the length of the longest subsequence.
Zillow
September 12, 20254
15
3,700 solved
Given a binary tree, write a function to find the longest subsequence of nodes such that each node in the subsequence is an ancestor of the next node. The function should return the length of this longest subsequence. The input will be the root node of the binary tree, and the output should be an integer representing the length of the longest subsequence.
This coding problem is frequently asked during Onsite at Zillow. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Zillow expects candidates to write production-quality code, not just solve the puzzle.
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 happens if the input contains duplicates?
- How would your solution change if the input was sorted?
- Can you solve this iteratively instead of recursively (or vice versa)?
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 solve the problem of finding the longest subsequence of nodes in a binary tree where each node is an ancestor of the next, we can utilize a depth-first search (DFS) approach. This is because we nee...
Approach
- Start from the root of the binary tree. Initialize a variable to keep track of the maximum length of subsequence found.
- Use a recursive DFS function that takes the current node and the current l...