Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent).
Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent).
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 sl(n, is_left=False):
if not n: return 0
if not n.l and not n.r: return n.v if is_left else 0
return sl(n.l, True) + sl(n.r, False)
print(sl(build([3, 9, 20, None, 4, 15, 7, 6])))What is printed?- A. 21
- B. 30
- C. 15
- D. 34
Correct answer: A. 21
Tree: 3 → (9, 20); 9 → (−, 4); 20 → (15, 7); 4 → (6, −). Left leaves: 6 (left child of 4) and 15 (left child of 20) = 21. 9 is a left child but not a leaf; 4 is a right child.
More Coding Interview Problems questions
- Problem: List every root-to-leaf path whose values sum to the target. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers. python class T: def init(s, v): s.v, s.l, s.r =…
- Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards. python…
- Problem: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1)…
- Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls. python…
- Problem: Count the calls made by naive recursive Fibonacci versus a memoised version for n = 10. python from functools import lrucache…