Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 05:38
Show Gist options
  • Save charlespunk/4723364 to your computer and use it in GitHub Desktop.
Save charlespunk/4723364 to your computer and use it in GitHub Desktop.
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid sorting additional nodes in a data structure. NODE: This is not necessarily a binary search tree.
public static Node findCommonAncestor(Node root, Node first, Node second){
Result r = findCommonAncestorHelper(root, first, second);
if(r.state == 2) return r.cross;
else return null;
}
public static Result findCommonAncestorHelper(Node thisNode, Node n, Node m){
if(thisNode == null) return Result(null, 0);
Result leftResult = findCommonAncestor(thisNode.left, n, m);
if(leftResult.state == 2) return leftResult;
Result rightResult = findCommonAncestor(thisNode.right, n, m);
if(rightResult.state == 2) return rightResult;
int state = leftResult.state + rightResult.state;
if(thisNode == n && thisNode == m) state += 2;
else if(thisNode == n || thisNode == m) state++;
Result result = new Result(null, state);
if(state == 2) result.cross = thisNode;
return result;
}
class Result{
Node cross;
int state;
retult(Node n, int i){
cross = n;
state = i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment