Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes).
Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes).
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]
best = 0
def height(nd):
global best
if not nd: return 0
l, r = height(nd.l), height(nd.r)
best = max(best, l + r)
return 1 + max(l, r)
height(build([1, 2, 3, 4, 5, None, None, 6, None, None, 7, 8]))
print(best)What is printed?- A. 4
- B. 6
- C. 7
- D. 5
Correct answer: D. 5
Tree: 1 → (2, 3), 2 → (4, 5), 4 → 6 → 8 and 5 → 7. The path 8–6–4–2–5–7 has 5 edges; the path from 8 up to the root and down to 3 also has 5. Counting nodes instead of edges would give 6.
More Coding Interview Problems questions
- 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…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right using its current neighbours (1 beyond the ends). Maximise the…
- Problem: Count the ways to split s into a sequence of dictionary words. python def count(s, words): W = set(words); dp = [1] + [0] len(s)…