Question

I got this question in a programming interview. Feel free to think about how you might answer it.

You're given the root node of a binary tree (not a binary search tree) where each node contains an integer value, and no value appears twice. You're also given two values val1 and val2 (which may or may not be in the tree.) If both are in the tree, return the node that is the least common ancestor of the two nodes containing these two values. If not, return null.

Assume that each node has access to the left and right children. You may append the node structure, but you may not append the parent to each node. Your algorithm should run in less than O(N^2), where N is the number of nodes in the tree.

NOTE: Although it's similar to the famous least-common-ancestor problem, the limitations in this one makes it not quite the same.

Was it helpful?

Solution

I don't understand why you would consider O(N2), unless I'm misunderstanding the problem. The following solution is a preorder traverse and therefore visits each node at most once:

struct node* visit(struct node* visited, int p, int q, struct node* sentinel) {
  if (!visited) return visited;
  if (visited->data == p || visited->data == q) {
    struct node* t;
    if ((t = visit(visited->left, p, q, visited))) return t;
    if ((t = visit(visited->right, p, q, visited))) return t;
    return sentinel;
  } else {
    struct node* left = visit(visited->left, p, q, visited);
    struct node* right = visit(visited->right, p, q, visited);
    if (left == visited) return right ? right : sentinel;
    if (right == visited) return left ? left : sentinel;
    return left ? left : right;
  }
}

struct node* lca(struct node* root, int val1, int val2) {
  return visit(root, val1, val2, 0);
}

I suppose some explanation is in order, but maybe since it was just a brain teaser, it's best to leave that code there and see what people make of it. (And I haven't tested it thoroughly either, to make it look more like an interview.)

This is not a question I've ever used in an interview, and I'm not sure what I would have made had someone come up with the above code as an answer. But then I've never been sure that I would have hired myself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top