|
| 1 | +package trees.commonancestorbinarytree; |
| 2 | + |
| 3 | +import trees.model.BinarySearchTree; |
| 4 | +import trees.model.SearchNode; |
| 5 | + |
| 6 | +/** |
| 7 | + * Find common ancestor of two nodes in a binary tree (not necessarily BST) |
| 8 | + * Created by techpanja |
| 9 | + * Created on 1/24/14 1:04 PM. |
| 10 | + */ |
| 11 | +public class CommonAncestorBinaryTree { |
| 12 | + |
| 13 | + public static SearchNode findCommonAncestor(BinarySearchTree searchTree, |
| 14 | + SearchNode node1, |
| 15 | + SearchNode node2) { |
| 16 | + return findCommonAncestor(searchTree.getRootOfTree(), node1, node2); |
| 17 | + } |
| 18 | + |
| 19 | + private static SearchNode findCommonAncestor(SearchNode rootOfTree, SearchNode node1, SearchNode node2) { |
| 20 | + if (rootOfTree == null) { |
| 21 | + return null; |
| 22 | + } |
| 23 | + |
| 24 | + // if either of node1 or node2 itself is the common ancestor. |
| 25 | + if (rootOfTree == node1 || rootOfTree == node2) { |
| 26 | + return rootOfTree; |
| 27 | + } |
| 28 | + |
| 29 | + // Check if node1 and node2 are in the left subtree of root. |
| 30 | + boolean isNode1OnLeft = isLeftOrRightNode((SearchNode) rootOfTree.getLeftChild(), node1); |
| 31 | + boolean isNode2OnLeft = isLeftOrRightNode((SearchNode) rootOfTree.getLeftChild(), node2); |
| 32 | + |
| 33 | + // If node1 and node2 on left and right branches of current root, root is the common ancestor. |
| 34 | + if (isNode1OnLeft != isNode2OnLeft) { |
| 35 | + return rootOfTree; |
| 36 | + } |
| 37 | + |
| 38 | + // if node1 and node2 and on the same side then decide on which side of the root to proceed. |
| 39 | + SearchNode newRoot = (SearchNode) (isNode1OnLeft ? rootOfTree.getLeftChild() : rootOfTree.getRightChild()); |
| 40 | + return findCommonAncestor(newRoot, node1, node2); |
| 41 | + } |
| 42 | + |
| 43 | + /* |
| 44 | + * Returns true if given node is in the subTree of root. |
| 45 | + * */ |
| 46 | + private static boolean isLeftOrRightNode(SearchNode root, SearchNode node) { |
| 47 | + if (root == null) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + if (root == node) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + boolean isLeft = isLeftOrRightNode((SearchNode) node.getLeftChild(), node); |
| 54 | + boolean isRight = isLeftOrRightNode((SearchNode) node.getRightChild(), node); |
| 55 | + return isLeft || isRight; |
| 56 | + } |
| 57 | +} |
0 commit comments