Data Structures & AlgorithmsHardAmazon · Microsoft OA
Find the bug: this BST validator compares each node only with its own children.
Find the bug: this BST validator compares each node only with its own children.
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
nodes = [T(x) if x is not None else None for x in xs]
kids = iter(nodes[1:])
for nd in nodes:
if nd:
nd.l = next(kids, None); nd.r = next(kids, None)
return nodes[0]
def valid(nd):
if not nd: return True
if nd.l and nd.l.v >= nd.v: return False
if nd.r and nd.r.v <= nd.v: return False
return valid(nd.l) and valid(nd.r)
print(valid(build([10, 5, 15, None, None, 6, 20])))What is printed?- A. True
- B. False
- C. None
- D. It raises an AttributeError
Correct answer: A. True
Every parent–child pair is ordered, so it prints True, but 6 sits in the right subtree of 10 and violates the BST property. A correct check passes down (low, high) bounds, or verifies that the inorder traversal is strictly increasing.
More Coding Interview Problems questions
- A binary tree with 12 nodes is serialised in preorder, writing '#' for every missing child. How many '#' markers appear?
- Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes). python class T: def init(s, v)…
- Problem: A node of a directed graph is 'safe' if every path from it ends at a terminal node (no outgoing edges). List the safe nodes…
- Problem: Find the bridges and articulation points of an undirected graph using DFS discovery times and low-links. python import sys…
- Problem: Count the strongly connected components and the number of edges in the condensation DAG (Kosaraju). python n = 8 E =…
- Problem: Check whether each graph is bipartite with BFS 2-colouring (graphs may be disconnected). python from collections import deque def…