Skip to content

Commit 6363289

Browse files
EASY/src/easy/LowestCommonAncestorOfABinarySearchTree.java
1 parent ca1c0e8 commit 6363289

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package easy;
2+
3+
import classes.TreeNode;
4+
5+
public class LowestCommonAncestorOfABinarySearchTree {
6+
//After drawing out the tree and run it manually, made it AC'ed easily! Cheers!
7+
8+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
9+
if(root == null || p == root || q == root) return root;
10+
if((root.val - p.val) * (root.val - q.val) <= 0) return root;
11+
if((root.val - p.val) * (root.val - q.val) > 0 && (root.val - q.val) > 0) {
12+
return lowestCommonAncestor(root.left, p, q);
13+
}
14+
if((root.val - p.val) * (root.val - q.val) > 0 && (root.val - q.val) < 0) {
15+
return lowestCommonAncestor(root.right, p, q);
16+
}
17+
return root;
18+
}
19+
20+
}

0 commit comments

Comments
 (0)