Thursday, December 26, 2013


Question for Sr Java Developer @ Google

Find the nearest common parent of two nodes of a binary tree?


Start with an ordinary depth-first search algorithm:
public void find(Node node, int target) {
    if(node == null || node.value == target) {
        return node;
    }
    if(node.value > target) {
        return find(node.left, target);
    } else {
        return find(node.right, target);
    }
}
Now, adapt this to take two "target" parameters, target1 and target2.
When the search for target1 takes you left, and the search for target2 takes you right, you've found the LCA.
This assumes that both targets actually do exist. If you need to assert that they do, you'll need to continue the search after finding the potential LCA.
public void findLca(Node node, int t1, int t2) {
    if(node == null) {
        return null;
    }
    if(node.value > t2 && node.value > t1) {
        // both targets are left
        return findLca(node.left, t1, t2);
    } else if (node.value < t2 && node.value < t1) {
        // both targets are right
        return findLca(node.right, t1, t2);
    } else {
        // either we are diverging or both targets are equal
        // in both cases so we've found the LCA
        // check for actual existence of targets here, if you like
        return node;
    }
}

No comments: