Skip to content

Commit cdf7517

Browse files
author
rpanjrath
committed
Updating readme
1 parent 986d375 commit cdf7517

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ Trees
255255
Link: https://github.com/techpanja/interviewproblems/blob/master/src/trees/checksubtree/CheckSubtree.java
256256

257257
3. Find common ancestor of two nodes in a binary tree (not necessarily BST).
258-
Link:
258+
Link:
259259

260260
4. Find diameter Of Tree.
261261
Link: https://github.com/techpanja/interviewproblems/blob/master/src/trees/diameteroftree/DiameterOfTree.java
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)