Skip to content

Commit 0dec287

Browse files
committed
Some optimization in LCA in BT
1 parent 8a563ab commit 0dec287

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/main/java/com/ctci/treesandgraphs/FirstCommonAncestor.java

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ public class FirstCommonAncestor {
1717
* - Returns q, if root's subtree includes q (and not p).
1818
* - Returns null, if neither p nor q are in root's subtree.
1919
* - Else, returns the common ancestor of p and q.
20+
* <p>
21+
* See {@link com.rampatra.trees.LeastCommonAncestorInBT} for a simpler version.
2022
*
2123
* @param root
2224
* @param a

src/main/java/com/rampatra/trees/LeastCommonAncestorInBT.java

+9-3
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,18 @@ public String toString() {
2929
private static TreeNode findLCA(TreeNode root, TreeNode node1, TreeNode node2) {
3030
if (root == null) return null;
3131

32+
/*
33+
optimal: check this first before checking the child nodes recursively because even if the other node
34+
is in one of the sub-trees the LCA would be root node
35+
*/
36+
if (root == node1 || root == node2) {
37+
return root;
38+
}
39+
3240
TreeNode left = findLCA(root.left, node1, node2);
3341
TreeNode right = findLCA(root.right, node1, node2);
3442

35-
if (root == node1 || root == node2) {
36-
return root;
37-
} else if (left != null && right != null) { // one node is in the left sub-tree and the other on the right sub-tree
43+
if (left != null && right != null) { // one node is in the left sub-tree and the other on the right sub-tree
3844
return root;
3945
} else if (left != null) { // we found one node in the left sub-tree
4046
return left;

0 commit comments

Comments
 (0)