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 must maintain the k-th smallest element in a data set while a high-throughput stream of insertions and deletions arrives. Propose a solution suitable for SRE in terms of memory and latency, then implement a working version in Python using two heaps (min-heap and max-heap) to support k-th queries efficiently. Discuss trade-offs versus an order-statistic augmented BST.
Write a Python function that converts the leaves of a binary tree into a doubly-linked list in left-to-right order, reusing the existing left/right pointers as prev/next for list nodes. Signature: leaves_to_dll(root: TreeNode) -> TreeNode (head). Achieve O(n) time and O(h) auxiliary space. Do not allocate new nodes for non-leaf nodes; only link leaves.
Implement is_valid_bst(root: TreeNode) -> bool in Python that checks whether a binary tree is a valid binary search tree (left < node < right). Assume duplicates are NOT allowed. Handle empty trees, very deep skewed trees, and explain both recursive min/max and iterative inorder approaches for correctness and performance.
Write a Python function to compute the height (max depth) of a binary tree and to determine whether the tree is height-balanced (difference of heights <= 1 for every node). Aim for an O(n) time algorithm and explain why a naive approach can be O(n^2). Discuss how balance checks affect production latency when applied frequently by SRE monitoring jobs.
Implement inorder traversal of a binary tree in Python. Provide both recursive and iterative (explicit stack) implementations. Assume TreeNode class: class TreeNode: def init(self, val=0, left=None, right=None): self.val=val; self.left=left; self.right=right. Your functions should return a list of node values in inorder. Example: tree built from [4,2,5,1,3] should return [1,2,3,4,5]. Explain time and space complexity and handle edge cases such as empty root.
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.