Trees and Binary Search Trees Questions
Hierarchical structures: binary trees, binary search trees, balanced trees, and tries. Covers traversal orders (in/pre/post-order, level-order), insertion and deletion invariants, and using tree properties to achieve logarithmic search. A core mid-difficulty interview area and the basis for many indexing and lookup systems.
You are adding two helpers to a tree library: one reports the maximum root-to-leaf distance, and the other reports how far a specific node is from the root. How would you implement both in Python, and what conventions would you settle on up front so the API is not ambiguous?
Given a binary tree where node values may be negative, implement max_path_sum(root) in Python that returns the maximum sum of values along any path (path may start and end at any nodes). Provide algorithmic explanation, handle negative-only trees, and justify correctness with post-order reasoning.
Given a binary tree where each node contains an integer value, implement can_partition_equal_sum(root) in Python that returns True if removing exactly one edge produces two subtrees with equal sum of node values. Aim for O(n) time and O(n) space. Discuss integer overflow considerations and how this problem might relate to partitioning features or compute graphs in ML systems.
Write a level-order (breadth-first) traversal function in Python that returns a list of lists, where each inner list contains the values at one tree depth. Use an explicit queue and ensure O(n) time and O(w) space where w is tree width. Mention why level-order serialization is often used for checkpointing tree-based models.
Given a sorted array of unique integers, implement a Python function that converts it into a height-balanced binary search tree (BST) with minimal height. The function should run in O(n) time. Describe the recursion invariant and expected height for n elements.
Unlock Full Question Bank
Get access to all Trees and Binary Search Trees interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.