Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (number of nodes in a complete binary tree in O(log² n))
What is printed? (number of nodes in a complete binary tree in O(log² n))
def count(n_nodes):
# implicit complete tree with nodes 1..n_nodes (heap numbering)
def left_h(i):
h = 0
while i <= n_nodes: h += 1; i = 2 * i
return h
def right_h(i):
h = 0
while i <= n_nodes: h += 1; i = 2 * i + 1
return h
def go(i):
if i > n_nodes: return 0
lh, rh = left_h(i), right_h(i)
if lh == rh: return (1 << lh) - 1
return 1 + go(2 * i) + go(2 * i + 1)
return go(1)
print(count(12), count(15), count(1))- A. 11 15 1
- B. 12 16 1
- C. 12 15 1
- D. 12 15 0
Correct answer: C. 12 15 1
If the leftmost and rightmost depths from a node are equal, its subtree is perfect with 2^h − 1 nodes and needs no further recursion; otherwise recurse. Only one branch per level recurses, giving O(log² n) instead of visiting all n nodes.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (AVL: which rotation is needed after inserting 30, 10, 20 into an empty AVL tree?) python def balancecase(order): a, b, c…
- What is the minimum number of nodes in an AVL tree of height h (height of a single node = 0)? python def nmin(h): a, b = 1, 2 # N(0), N(1)…
- BFS from vertex 0 visits neighbours in increasing order. What is the BFS order and the DFS (recursive) order? python g = {0: [1, 2], 1…
- Run Dijkstra from A on the weighted directed graph. In what order are vertices finalised (popped), and what is dist[E]? python import…
- Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight? python import…
- Kahn's topological sort with a FIFO queue (initial zero-indegree vertices in increasing order). What is printed? python from collections…