Binary Trees Interview Questions [2026-2027]

456+ real questions from verified interview reports across 12 companies.

Sourced from 1Point3Acres, Blind, Glassdoor, Reddit, and more. Translated and cleaned.

456
Questions
12
Companies
12
Top Askers

Top Companies Asking Binary Trees Questions

Sample Binary Trees Questions

Round 1: Introduction and short discussion on my current work and product. DS / ALGO 1. Top View of a Binary Tree (Code) 2. Check if given Tree is BST or...

Question 1-Debugging (Find Minimum in the array (1 Line of code change)(Very Easy) ) Question 2- Coding (Find Sign of product of all element in an array multiplied Together.E.g: given an...

YOE: 4 years Round 1: Introduction and short discussion on my current work and product. DS / Algo 1. Top View of a Binary Tree (Code) 2. Check if given Tree is BST or...

**Candidate Profile** * **Experience:** 2 Years * **Tech Stack:** Python * **Date:** December 1, 2025 **Technical Assessment** The interview focused on two primary algorithmic challenges: 1. **Search

Cohesity Interview Experience – Binary Tree DP (Learning Moment) Recently, I interviewed with Cohesity and wanted to share one learning experience from the round. The interview started with a ~10 minu

Aptitude and Coding RoundThis round consisted of 12 questions including 10 general aptitude and 2 coding questions. The aptitude part comprised of questions on speed, dis...

BlackRock visited our campus for a recruitment drive, providing an exciting opportunity for students to showcase their skills and secure positions in their esteemed organi...

Introduction:Amadeus Labs started hiring from our college for the first time from our batch, On the first day at 9.30 am the company hosted a virtual meeting to share thei...

There were 6 rounds in total.1) Online coding - hackerearthThree Questions in 1.15hr. Total 50 marks.Questions were in increasing order of the difficulty as per the marks....

I recently had interview at Belzabar.After aptitude round only 69 students were shortlisted out of 256.First Round(F2F):He started asking questions about data structure. Q...

LeetCode #652: Find Duplicate Subtrees. Difficulty: Medium. Topics: Hash Table, Tree, Depth-First Search, Binary Tree. Asked at Yandex in the last 6 months.

LeetCode #236: Lowest Common Ancestor of a Binary Tree. Difficulty: Medium. Topics: Tree, Depth-First Search, Binary Tree. Asked at Yandex in the last 6 months.

LeetCode #297: Serialize and Deserialize Binary Tree. Difficulty: Hard. Topics: String, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree. Asked at Quora in the last 6 months.

LeetCode #98: Validate Binary Search Tree. Difficulty: Medium. Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. Asked at Millennium in the last 6 months.

LeetCode #2791: Count Paths That Can Form a Palindrome in a Tree. Difficulty: Hard. Topics: Hash Table, Bit Manipulation, Tree, Depth-First Search. Asked at WeRide in the last 6 months.

LeetCode #979: Distribute Coins in Binary Tree. Difficulty: Medium. Topics: Tree, Depth-First Search, Binary Tree. Asked at Zeta Global in the last 6 months.

LeetCode #297: Serialize and Deserialize Binary Tree. Difficulty: Hard. Topics: String, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree. Asked at Hive in the last 6 months.

## Problem Design a layer system for a graphics application. Each layer has: `id`, `content` (2D pixel grid), `opacity` (0.0-1.0), `blend_mode` ("normal"|"multiply"|"screen"), and `visible` flag. Implement: - `add_layer(layer, position)` — insert layer at given z-position. - `flatten() -> Grid` — composite all visible layers top-to-bottom using their blend modes. - `move_layer(id, new_position)` — reorder layer. - `set_opacity(id, opacity)` — update layer opacity. ```python class LayerSystem: def add_layer(self, layer: Layer, position: int) -> None: ... def flatten(self) -> list[list[tuple[int,int,int]]]: ... def move_layer(self, layer_id: str, new_pos: int) -> None: ... def set_opacity(self, layer_id: str, opacity: float) -> None: ... # Blend formulas (per channel, 0-255): # normal: result = top * opacity + bottom * (1 - opacity) # multiply: result = (top * bottom / 255) * opacity + bottom * (1-opacity) # screen: result = (255 - (255-top)*(255-bottom)/255) * opacity + bottom*(1-opacity) ``` ## Follow-ups 1. `flatten` recomputes from scratch every call. How would you cache intermediate composites and invalidate on change? 2. What data structure best represents the layer stack for efficient reordering? 3. How does the order of compositing (top-to-bottom vs bottom-to-top) affect the blend result? 4. Describe how Photoshop's layer panel maps to your class design.

## Problem You have a permission tree where each node has an `id`, a `parent_id`, and an `access_level` (0=public, 1=restricted, 2=private). A user has a clearance level. A node is accessible if `user_clearance >= node.access_level` AND all ancestors are accessible. Given a target node and a user clearance, find the topmost accessible ancestor — the highest node in the path from root to target that the user can access. If the root itself is accessible, return the root. ```python def topmost_accessible( nodes: dict[str, dict], # id -> {parent_id, access_level} target_id: str, user_clearance: int ) -> str | None: ... ``` ``` Tree: root(0) -> dept(1) -> team(2) -> doc(2) User clearance = 1 Path root->dept->team->doc Accessible: root(ok), dept(ok), team(fail), doc(fail) Topmost accessible = "dept" ``` ## Follow-ups 1. If the root itself is inaccessible, what do you return? 2. How does your solution change if permission inheritance can be broken (a public node under a private one)? 3. For a tree with 1 million nodes, you need to answer 10,000 topmost-accessible queries per second. How do you precompute or cache? 4. Extend to support group-based permissions (user belongs to groups; a node grants access to a group). How does this change the lookup?

## Problem Design a backend API for managing hierarchical data (e.g., org charts, category trees). Each node has an `id`, `name`, `parent_id`, and optional `metadata`. Implement these endpoints: ``` POST /nodes - create a node (specify parent_id or null for root) GET /nodes/:id - get a node and its direct children GET /nodes/:id/subtree - get a node and all descendants PUT /nodes/:id - update name or metadata DELETE /nodes/:id - delete node and all descendants PUT /nodes/:id/move - move subtree to a new parent ``` ## Example ``` POST /nodes {"name": "Engineering", "parent_id": null} -> {"id": "1"} POST /nodes {"name": "Backend", "parent_id": "1"} -> {"id": "2"} POST /nodes {"name": "Frontend", "parent_id": "1"} -> {"id": "3"} GET /nodes/1/subtree -> {"id":"1", "children": [{"id":"2"}, {"id":"3"}]} PUT /nodes/2/move {"new_parent_id": "3"} -> Backend becomes child of Frontend ``` ## Follow-ups 1. What database representation (adjacency list, nested sets, closure table, path enumeration) fits best for this use case? 2. How do you implement `GET /subtree` efficiently without loading the whole table? 3. How do you prevent a `move` operation from creating a cycle?

## Problem You are given a list of `(employee, manager)` pairs representing a company org chart. The root node has no manager. Print the hierarchy as an indented ASCII tree where each level of depth adds 2 spaces. ```python def print_hierarchy(pairs: list[tuple[str, str]]) -> None: pass ``` **Example:** ``` pairs = [("Bob","Alice"),("Carol","Alice"),("Dave","Bob"),("Alice",None)] output: Alice Bob Dave Carol ``` ## Approach Build an adjacency list (parent -> children). DFS from the root, passing current depth to compute indent. Sort children alphabetically for determinism. ## Follow-ups 1. What if the input contains a cycle (data error)? How do you detect and report it? 2. The company has 1 million employees. The recursion overflows the call stack. How do you convert the DFS to iterative? 3. Add the ability to print only the subtree rooted at a given employee. 4. Output valid JSON instead of ASCII, preserving the nested hierarchy structure.

## Problem Find the lowest common ancestor of two nodes in a binary tree or binary search tree. ## Likely LeetCode equivalent LeetCode 236 - Lowest Common Ancestor of a Binary Tree. ## Tags binary_tree,recursion,dfs,swe

## Round 1 - Coding ## Problem Given a tree (not necessarily binary), where each node has an ID and a list of children, return a list where the `i`-th element is the number of nodes at depth `i` (root is depth 0). ```python class TreeNode: def __init__(self, node_id: int, children: list['TreeNode'] = None): self.node_id = node_id self.children = children or [] def count_per_level(root: TreeNode) -> list[int]: ... ``` ## Example ``` 1 / | \ 2 3 4 /| | 5 6 7 count_per_level(root) # Level 0: [1] -> 1 # Level 1: [2,3,4] -> 3 # Level 2: [5,6,7] -> 3 # -> [1, 3, 3] ``` ## Follow-ups 1. How do you implement this iteratively using a queue versus recursively? What are the trade-offs? 2. How would you extend this to return the sum of node values at each level? 3. Given two trees, how do you find the deepest common level where both trees have the same node count? 4. If the tree has millions of nodes, how do you process it level by level without running out of memory?

## Round 1 - Coding ## Problem Given a list of `(employee_id, manager_id)` pairs representing a company hierarchy, implement queries to find: direct reports, all reports in the subtree, the management chain to the root, and the lowest common manager of two employees. ```python class OrgChart: def __init__(self, reports: list[tuple[int, int]]): # reports: (employee_id, manager_id); root has manager_id = -1 ... def direct_reports(self, emp_id: int) -> list[int]: ... def all_reports(self, emp_id: int) -> list[int]: # entire subtree ... def management_chain(self, emp_id: int) -> list[int]: # emp -> root ... def lowest_common_manager(self, emp1: int, emp2: int) -> int: ... ``` ## Example ``` reports = [(2,1),(3,1),(4,2),(5,2),(6,3)] chart = OrgChart(reports) chart.direct_reports(1) -> [2, 3] chart.all_reports(2) -> [4, 5] chart.management_chain(5) -> [5, 2, 1] chart.lowest_common_manager(4, 6) -> 1 ``` ## Follow-ups 1. What is the time complexity of `lowest_common_manager`? How can you optimize it with preprocessing? 2. How would you handle an employee who reports to multiple managers (matrix org structure)? 3. How do you detect cycles in the reporting structure (e.g., employee A reports to B who reports to A)? 4. How would you store this hierarchy in a relational database and write a recursive CTE to fetch the full subtree?

## Problem Given a flat list of comment objects (each with an id and optional parent_id), reconstruct the nested tree structure and implement depth-first traversal for rendering. ```python from dataclasses import dataclass, field from typing import Optional @dataclass class Comment: id: int author: str body: str parent_id: Optional[int] children: list['Comment'] = field(default_factory=list) def build_tree(comments: list[Comment]) -> list[Comment]: # Returns list of root-level comments with children populated pass def render_thread(roots: list[Comment], indent: int = 0) -> str: pass ``` **Example:** ``` comments = [ Comment(1, "alice", "First!", None), Comment(2, "bob", "Reply to first", 1), Comment(3, "carol", "Reply to bob", 2), ] build_tree(comments) -> [Comment(1, children=[Comment(2, children=[Comment(3)])])] ``` ## Follow-ups 1. What data structure makes `build_tree` run in O(n) rather than O(n^2)? 2. How would you handle orphaned comments (parent_id points to a non-existent comment)? 3. How would you sort children by score (upvotes - downvotes) at each level? 4. How would you implement lazy loading so deep sub-threads are only fetched on expand?

See All 456 Binary Trees Questions

Full question text, interview context, and company-specific frequency data for subscribers.

Get Access

Related Topics