Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def build(xs, i=0):
if i >= len(xs) or xs[i] is None: return None
return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def h(t):
return 0 if not t else 1 + max(h(t.l), h(t.r))
print(h(build([1, 2, 3, None, 5, None, None, None, None, 8])))What is printed?- A. 3
- B. 5
- C. 2
- D. 4
Correct answer: D. 4
Post-order: a node's height is 1 + the larger child height. The path 1 → 2 → 5 → 8 has 4 nodes (index 9 is the left child of index 4). Counting edges instead of nodes gives 3. O(n) time, O(h) stack.
More Coding Interview Problems questions
- Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has…
- Problem: Return the right-side view of a tree (the last node of each level). Trees are built by build(xs): a level-order list where index…
- Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. Trees are built by…
- Problem: Find the lowest common ancestor of two keys in a BST. Trees are built by build(xs): a level-order list where index i has children…
- Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2…
- Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. Trees are built by build(xs): a…