InterviewDB Question · Los Angeles

Decision Tree - Implement Predict Traversal for a Binary Classification Tree

Question Details

Problem

A decision tree is stored as a list of nodes. Each node has: feature_index (int or None for leaf), threshold (float or None), left (child index), right (child index), value (class label, set only on leaves).

Given this structure and a feature vector, implement predict.

python
class TreeNode:
    feature_index: int | None
    threshold: float | None
    left: int | None
    right: int | None
    value: int | None  # only on leaf

def predict(nodes: list[TreeNode], features: list[float]) -> int:
    # traverse from node 0; go left if features[node.feature_index] <= threshold

Example

# Tree: if x[0] <= 3.5 -> predict 0, else if x[1] <= 7.0 -> predict 1, else predict 2
features = [5.0, 8.0]

**Output**: 2

Follow-ups

  1. How would you implement predict_proba that returns class probabilities instead of a hard label?
  2. How do you handle missing feature values at inference time?
  3. Extend to a random forest: given n trees,

return the majority vote class.
4. Describe how you would serialize and load this tree from a JSON file.

Full Details

Problem

A decision tree is stored as a list of nodes. Each node has: feature_index (int or None for leaf), threshold (float or None), left (child index), right (child index), value (class label, set only on leaves).

Given this structure and a feature vector, implement predict.

python
class TreeNode:
    feature_index: int | None
    threshold: float | None
    left: int | None
    right: int | None
    value: int | None  # only on leaf

def predict(nodes: list[TreeNode], features: list[float]) -> int:
    # traverse from node 0; go left if features[node.feature_index] <= threshold

Example

# Tree: if x[0] <= 3.5 -> predict 0, else if x[1] <= 7.0 -> predict 1, else predict 2
features = [5.0, 8.0]

**Output**: 2

Follow-ups

  1. How would you implement predict_proba that returns class probabilities instead of a hard label?
  2. How do you handle missing feature values at inference time?
  3. Extend to a random forest: given n trees,

return the majority vote class.
4. Describe how you would serialize and load this tree from a JSON file.

About This Question

This is a reported interview question from a affirm interview during the phone round.

It covers the following topics: Coding, Onsite, Phone .