Tree Interview Questions: BFS, DFS, BST and DP on Trees, The Complete Deep Dive for Product Company Rounds
The complete tree interview guide for product company rounds — Binary Trees, BST, BFS, DFS, Path Problems and DP on Trees with 25 company-tagged problems.

Posted by
Shahar Banu

Reviewed by
Divyansh Dubey
Published
You have seven years of real engineering experience. You build distributed payment systems at scale. But when someone asks you to serialize a binary tree in an Amazon interview, your mind blanks out. That specific terror is real, and it is far more common than most senior engineers admit. Tree interview questions appear in roughly 20% of all product company coding rounds in India, according to hiring data tracked across Amazon India, Google India, Flipkart, and Microsoft India interview pipelines in 2024 and 2025. The problem is not that you cannot solve these problems. The problem is that most resources treat trees as a beginner topic, when in reality, MAANG interviewers use trees to test recursive thinking, DP on trees, and pattern recognition simultaneously. This guide is the complete breakdown of every tree interview question pattern you will face. By the end, you will know exactly how to identify the pattern, write the code, and explain your reasoning in the way an L5 interviewer at Amazon expects.
The 4 Core Tree Problem Families You Must Master
Every tree interview question in India fits into one of four families. Recognising the family before you write code is what separates engineers who pass Amazon and Google rounds from those who freeze.
The four families are: traversal problems, BST problems, path problems, and DP on trees. Each family has a distinct set of signals in the problem statement. Traversal problems ask you to visit nodes in a specific order. BST problems leverage the sorted property of binary search trees. Path problems ask you to compute something along a root-to-leaf or any-node-to-any-node path. DP on trees builds optimal substructure across parent-child relationships.
Understanding this taxonomy matters for one practical reason: your solution approach changes completely depending on the family. A traversal problem needs an iterative queue or a simple recursive call. A DP on trees problem needs you to define state at each node and combine children's results correctly. Mixing them up mid-interview costs you the round.
Here is a direct answer block that MAANG interviewers often use as a filtering question: What are the main types of tree problems in product company interviews? Tree problems in product company interviews fall into four categories: traversal (BFS, DFS, level order), BST operations (validate, search, insert, delete), path problems (max path sum, LCA, root-to-leaf paths), and DP on trees (diameter, house robber on trees, maximum independent set). Each category requires a distinct pattern, not a uniform recursive template.
Senior engineers who have built real systems often try to over-engineer tree problems. Keep the solution clean. Amazon interviewers specifically reward clarity over cleverness at the L5 level.
Key takeaway: Identify the tree problem family before coding. The four families are traversal, BST, path, and DP on trees. Your solution template changes for each one.
Traversal Problems: BFS, DFS, and Level Order With Code
Traversal problems are the entry point for every tree section in a product company interview. They look simple. They are not. Interviewers at Flipkart and Microsoft India use traversal variants to check whether you understand iterative vs recursive tradeoffs, stack overflow risks on deep trees, and space complexity implications.
Depth First Search (DFS) has three variants: inorder (left, root, right), preorder (root, left, right), and postorder (left, right, root). For binary trees, inorder traversal of a BST gives a sorted sequence. Preorder is useful for serialization. Postorder is the natural fit for problems where you process children before parents.
# Inorder DFS - Recursive def inorder(root): if not root: return [] return inorder(root.left) + [root.val] + inorder(root.right) # Inorder DFS - Iterative (avoids stack overflow on deep trees) def inorder_iterative(root): result, stack = [], [] current = root while current or stack: while current: stack.append(current) current = current.left current = stack.pop() result.append(current.val) current = current.right return result
Try It Live
Copy Code
Breadth First Search (BFS) uses a queue. It processes nodes level by level. This is the correct approach for level order traversal, finding the minimum depth, and connecting nodes at the same level. In Python, use `collections.deque` for O(1) popleft operations.
from collections import deque def level_order(root): if not root: return [] result, queue = [], deque([root]) while queue: level_size = len(queue) level = [] for _ in range(level_size): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) return result
Try It Live
Copy Code
Time complexity for both DFS and BFS is O(n) where n is the number of nodes. Space complexity is O(h) for DFS (h is tree height) and O(w) for BFS (w is maximum width). For a balanced tree, O(h) is O(log n). For a skewed tree, it degrades to O(n). Always mention this in your interview.
If you want the complete data structures interview guide covering all traversal patterns across linked lists, trees, and graphs, that resource covers the full picture.
Key takeaway: Know both recursive and iterative implementations of DFS. Use BFS with a deque for level order problems. Always state the space complexity difference between the two approaches.
BST Problems: Validation, Search, Insert, and Delete
Binary search tree problems are a separate family. They rely entirely on one property: for every node, all values in the left subtree are strictly less, and all values in the right subtree are strictly greater. This property is the key to every BST interview question in India.
Validating a BST is a classic trap problem. The naive approach checks only whether `node.left.val < node.val` and `node.right.val > node.val`. This fails for this tree:
``` 5 / \ 1 4 / \ 3 6 ```
Node 4 satisfies the local check but violates the global BST property because 4 is in the right subtree of 5. The correct approach passes min and max bounds down the recursion.
def is_valid_bst(root, min_val=float('-inf'), max_val=float('inf')):
if not root:
return True
if root.val <= min_val or root.val >= max_val:
return False
return (is_valid_bst(root.left, min_val, root.val) and
is_valid_bst(root.right, root.val, max_val))
Try It Live
Copy Code
BST Search runs in O(log n) for balanced trees, O(n) for skewed trees. Always clarify this with your interviewer. BST Insert follows the same path as search. BST Delete has three cases: deleting a leaf (simple removal), deleting a node with one child (bypass the node), deleting a node with two children (replace with inorder successor or predecessor). The two-children case is where most candidates stumble.
For engineers preparing for Amazon India or Google India BST rounds, this is the insider knowledge that most resources skip: interviewers are not looking for the code alone. They are looking for whether you can explain all three deletion cases and their edge conditions before writing a single line. Engineers who state the cases verbally first, then code, score higher on the communication rubric at Amazon.
Check out the top 100 LeetCode problems for MAANG interviews to see which BST problems appear most frequently in Amazon and Google pipelines.
Key takeaway: BST validation requires passing min and max bounds, not local comparisons. BST deletion has three cases. Name all three before you code in an interview setting.
Only 4 Seats Left — Cohort 3
Crack Tree Rounds at Amazon and Google
Practice every BST, BFS, DFS and DP on Trees pattern with timed mocks and a 1:1 FAANG mentor who has passed the exact L5 rounds you are targeting.
Path Problems: Max Path Sum, Root to Leaf, and LCA
Path problems are where tree interview questions in India get genuinely difficult. These are the problems that separate L4 from L5 candidates at Amazon and Google India. The reason: path problems require you to define what a "path" means in that specific problem, and the definition changes every time.
Maximum Path Sum (LeetCode 124) is the canonical hard tree problem. A path here means any sequence of nodes where each pair of adjacent nodes has an edge, and nodes can only appear once. The path does not need to pass through the root.
def max_path_sum(root):
max_sum = [float('-inf')]
def helper(node):
if not node:
return 0
left_gain = max(helper(node.left), 0)
right_gain = max(helper(node.right), 0)
# Path through current node
path_sum = node.val + left_gain + right_gain
max_sum[0] = max(max_sum[0], path_sum)
# Return max gain if continuing upward
return node.val + max(left_gain, right_gain)
helper(root)
return max_sum[0]
Try It Live
Copy Code
The critical insight is that you compute two things at each node: the maximum path through that node (for updating the global answer) and the maximum gain you can contribute to your parent (which can only go one direction, left or right, never both). This distinction is what most candidates miss in live interviews.
Root to Leaf paths are simpler: use DFS and track the current path. The key edge case is single-node trees. Always check for it explicitly.
Lowest Common Ancestor (LCA) is one of the most frequently asked binary tree interview questions in India across Amazon, Google, and Flipkart. The recursive solution is elegant: if a node equals p or q, return it. Otherwise, recurse left and right. If both sides return non-null, the current node is the LCA. If only one side returns non-null, propagate it upward.
def lca(root, p, q): if not root or root == p or root == q: return root left = lca(root.left, p, q) right = lca(root.right, p, q) if left and right: return root return left if left else right
Try It Live
Copy Code
Time complexity: O(n). Space complexity: O(h). For Google interviews, mention that LCA on a BST is more efficient because you can use the BST property to guide your search in O(log n) for a balanced tree.
For engineers who want to understand how path problems connect to graph traversal patterns, the Union-Find and Disjoint Set guide covers the graph-level extension of connectivity problems.
Key takeaway: Path problems require defining "path" precisely before coding. Max Path Sum uses a global max and a one-direction gain value. LCA uses the property that if both subtrees return a result, the current node is the answer.
DP on Trees: Diameter, House Robber III, and Maximum Sum
DP on trees is the highest-difficulty family of tree interview questions. These problems appear in senior SDE rounds at Amazon India and Google India. If you are targeting L5 or SDE II, this section is where your preparation needs to go deep.
The core idea behind DP on trees: define a state for each node that captures the optimal subproblem answer for its subtree. Then combine children's states at each parent. The recursion does the state propagation naturally.
Diameter of a Binary Tree is the longest path between any two nodes. It does not need to pass through the root. The trick is identical to Max Path Sum: at each node, compute the diameter through that node (left height plus right height) and propagate the maximum height upward.
def diameter(root): max_diameter = [0] def height(node): if not node: return 0 left_h = height(node.left) right_h = height(node.right) max_diameter[0] = max(max_diameter[0], left_h + right_h) return 1 + max(left_h, right_h) height(root) return max_diameter[0]
Try It Live
Copy Code
House Robber III (LeetCode 337) is the clearest DP on trees problem. You cannot rob two directly connected nodes. At each node, you have two choices: rob this node (and skip children) or skip this node (and take the best from children).
def rob(root): def dp(node): if not node: return (0, 0) # (rob this node, skip this node) left = dp(node.left) right = dp(node.right) rob_current = node.val + left[1] + right[1] skip_current = max(left) + max(right) return (rob_current, skip_current) return max(dp(root))
Try It Live
Copy Code
The nuance here: returning a tuple `(rob, skip)` from each recursive call avoids recomputation entirely. This is a O(n) solution. A naive memoized solution using a dictionary also works but is slightly more verbose. For Flipkart and Microsoft India rounds, either approach is accepted. For Amazon, the interviewer will likely ask you to optimize if you present the naive version first.
In 2026, some engineers ask whether studying DP on trees matters when GitHub Copilot can generate the recursive skeleton. The answer is yes, because the copilot cannot define the correct state or explain the combining logic under interview pressure. MAANG interviewers explicitly test your ability to reason about recursive state, not just produce working code.
The Dynamic Programming deep dive guide covers how to think about state definition across all DP problem types, including DP on trees.
Key takeaway: DP on trees defines state per node and combines children's states. Return a tuple (take, skip) or (include, exclude) to propagate both choices upward without recomputation.
The 25 Most Asked Tree Interview Questions: Company-Tagged
Here is the curated list of binary tree interview questions and BST interview questions asked in product company rounds in India, tagged by company based on community-reported interview data from 2023 to 2025.
Amazon India (appears frequently in SDE II and L5 rounds):
1. Binary Tree Level Order Traversal (LeetCode 102)
2. Serialize and Deserialize Binary Tree (LeetCode 297)
3. Lowest Common Ancestor of a Binary Tree (LeetCode 236)
4. Binary Tree Maximum Path Sum (LeetCode 124)
5. Construct Binary Tree from Preorder and Inorder Traversal (LeetCode 105)
6. Flatten Binary Tree to Linked List (LeetCode 114)
Google India (frequently in onsite rounds):
7. Diameter of Binary Tree (LeetCode 543)
8. Binary Tree Right Side View (LeetCode 199)
9. Vertical Order Traversal of a Binary Tree (LeetCode 987)
10. Count Complete Tree Nodes (LeetCode 222)
11. Path Sum II (LeetCode 113)
12. Sum Root to Leaf Numbers (LeetCode 129)
Flipkart (SDE I and SDE II rounds):
13. Validate Binary Search Tree (LeetCode 98)
14. Kth Smallest Element in a BST (LeetCode 230)
15. Delete Node in a BST (LeetCode 450)
16. Symmetric Tree (LeetCode 101)
17. Maximum Depth of Binary Tree (LeetCode 104)
Microsoft India:
18. Invert Binary Tree (LeetCode 226)
19. Same Tree (LeetCode 100)
20. Subtree of Another Tree (LeetCode 572)
21. Balanced Binary Tree (LeetCode 110)
22. Populating Next Right Pointers in Each Node (LeetCode 116)
All companies (commonly asked in any product company round):
23. House Robber III (LeetCode 337)
24. Lowest Common Ancestor of a BST (LeetCode 235)
25. Binary Tree Zigzag Level Order Traversal (LeetCode 103)
Engineers with 7 or more years of experience often ask whether they should start from problem 1 or jump straight to the hard problems. The honest answer: if you have not done a structured DSA interview in years, spend one focused week on problems 1 to 10 to rebuild pattern recognition. Then move to 11 to 25 for depth. You do not need to start from arrays and strings. But you do need to rebuild the habit of thinking recursively under time pressure.
The structured DSA plan for working engineers covers exactly how to sequence this preparation within a one-hour daily practice window, which is realistic for engineers with family responsibilities.
How the DSA and System Design with AI Program Can Help You
The single biggest constraint for senior engineers targeting MAANG is not knowledge. It is structure and accountability within a busy schedule. You are building distributed payment systems during the day and managing a two-year-old in the evenings. The last thing you need is a program designed for a 23-year-old who can grind LeetCode for four hours after midnight.
The FutureJobs DSA and System Design with AI Program is built specifically for working professionals at the 5 to 10 year band. The schedule runs on evenings and weekends. Classes do not assume you have six free hours on a Tuesday. The program runs for five months, covers 240 or more hours of live instruction, and includes 1:1 mentorship from FAANG engineers who have passed the exact L5 and SDE II rounds you are targeting.
For a senior engineer at your level, the deciding factor is usually the mentor, not the content. You can find tree problems on LeetCode. What you cannot find on LeetCode is a conversation with an SDE II at Amazon who tells you exactly what the L5 interviewer cares about in the first five minutes of a coding round. That is what the FAANG mentor access at FutureJobs provides.
The program covers DSA patterns (including every tree family in this guide), HLD and LLD system design, and a Prompt Engineering module for AI-first interview readiness in 2026. The fee structure is pay-after-placement: roughly 50% upfront at an effective ₹5,000 and the remainder only after you secure a job offer. That is structurally different from Scaler or AlmaBetter, which charge ₹1.5 to 2.44 lakh upfront regardless of outcome. Over 700 engineers enrolled in the DSA program this month, and placement outcomes are tracked transparently through Impacteers' 25-year recruitment network.
Only 10 Seats Left — Cohort 3
No Time for a 5-Month Program? Read This First.
FutureJobs runs on evening and weekend schedules built for senior engineers with families, not for fresh graduates with free nights.
Frequently Asked Questions
How many tree problems do I need to solve to be ready for Amazon India interviews?
You need to solve 30 to 40 tree problems covering all four families: traversal, BST, path problems, and DP on trees. Quality over quantity matters more at senior levels. Solving 20 problems with full understanding of the recursive state and complexity analysis is more valuable than 60 problems rushed without pattern recognition. Amazon's SDE II and L5 rounds test reasoning, not recall.
I have not done DSA interviews since college. Is it too late to learn tree patterns at 30 with a full-time job and a family?
It is not too late. Engineers with 7 or more years of experience have a real advantage: you understand system constraints and can explain tradeoffs naturally. The gap is interview-specific pattern recognition, which is trainable in 12 to 16 weeks with one to two focused hours per day. The FutureJobs program is specifically designed for this constraint, with evening and weekend scheduling that does not require you to sacrifice family time.
Can I prepare for product company tree interviews while working at a fintech company full-time?
Yes, and the discipline you already have from managing production systems works in your favour. One to two hours per evening, three to four days per week, is enough to cover all 25 tree problems on this list within eight weeks. The key is structured sequencing: start with traversal patterns, move to BST, then path problems, and finish with DP on trees. Do not mix families randomly.
What is the difference between BFS and DFS for tree problems in interviews?
BFS uses a queue and processes nodes level by level, making it the right choice for level order traversal, minimum depth, and connecting nodes at the same level. DFS uses recursion or an explicit stack and processes nodes along a path, making it the right choice for path sum problems, tree construction, and DP on trees. Time complexity is O(n) for both. Space complexity is O(h) for DFS and O(w) for BFS, where h is height and w is maximum width.
How is FutureJobs different from Scaler or AlmaBetter for tree and DSA preparation?
FutureJobs differs structurally in two ways. First, the pay-after-placement model means you pay an effective ₹5,000 upfront versus ₹1.5 to 2.44 lakh upfront at Scaler or AlmaBetter. The financial incentive is aligned with your outcome, not your enrollment. Second, the 1:1 FAANG mentor model provides direct access to engineers who have passed the L5 rounds you are targeting, not just content coaches. For senior engineers, that mentor access is the differentiator.
How do product companies in India evaluate tree problems differently from DSA textbooks?
Amazon India and Google India evaluate tree problems on four dimensions: correctness, time and space complexity analysis, communication of your approach before coding, and edge case handling. Textbooks focus on correctness alone. In a live interview, stating "I will handle the null root case first, and this solution is O(n) time and O(h) space where h degrades to O(n) on a skewed tree" before writing code increases your score on the communication rubric significantly.
Final Thoughts
Tree interview questions in India are not going away. They are appearing more frequently in MAANG rounds in 2026, not less, because trees test the recursive thinking and state management that AI code generators cannot replicate under live interview pressure.
You now have the complete framework. The four families: traversal, BST, path, and DP on trees. The code templates for BFS, DFS, BST validation, LCA, Max Path Sum, Diameter, and House Robber III. The 25 most asked tree problems tagged by company. And the sequencing logic for how to prepare efficiently within real-world time constraints.
The next step is not to open LeetCode and solve 10 problems randomly. The next step is to pick one family, spend three focused sessions on it, and then solve five problems from that family with full complexity analysis written out. That is how pattern recognition builds. That is what an L5 interviewer at Amazon is testing when they give you a tree problem. Not whether you memorized the answer, but whether you have the structured thinking to arrive at it.
Your seven years of engineering experience is not a disadvantage in this process. It is the foundation that makes the thinking faster once the patterns click.
