File tree Expand file tree Collapse file tree 2 files changed +38
-2
lines changed Expand file tree Collapse file tree 2 files changed +38
-2
lines changed Original file line number Diff line number Diff line change 3
3
![ Hits] ( https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https://github.com/anishLearnsToCode/leetcode-algorithms )
4
4
![ made-with-java] ( https://img.shields.io/badge/Made%20with-Java-1f425f.svg )
5
5
![ made-with-python] ( https://img.shields.io/badge/Made%20with-Python-1f425f.svg )
6
- ![ problems-solved] ( https://img.shields.io/badge/Problems%20Solved-46 /1412-1abc9c.svg )
7
- ![ problems-solved-java] ( https://img.shields.io/badge/Java-45 /1412-1abc9c.svg )
6
+ ![ problems-solved] ( https://img.shields.io/badge/Problems%20Solved-58 /1412-1abc9c.svg )
7
+ ![ problems-solved-java] ( https://img.shields.io/badge/Java-57 /1412-1abc9c.svg )
8
8
![ problems-solved-python] ( https://img.shields.io/badge/Python-3/1412-1abc9c.svg )
9
9
[ ![ license] ( https://img.shields.io/badge/LICENSE-MIT-<COLOR>.svg )] ( LICENSE )
10
10
[ ![ PRs Welcome] ( https://img.shields.io/badge/PRs-welcome-brightgreen.svg )] ( CONTRIBUTING.md )
Original file line number Diff line number Diff line change
1
+ import java .util .ArrayList ;
2
+ import java .util .List ;
3
+
4
+ public class LowestCommonAncestorOfBinarySearchTree {
5
+ private static class TreeNode {
6
+ int val ;
7
+ TreeNode left ;
8
+ TreeNode right ;
9
+ }
10
+
11
+ public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
12
+ List <TreeNode > pathToP = pathTo (root , p );
13
+ List <TreeNode > pathToQ = pathTo (root , q );
14
+ return lowestCommonAncestor (pathToP , pathToQ );
15
+ }
16
+
17
+ private static List <TreeNode > pathTo (TreeNode root , TreeNode to ) {
18
+ List <TreeNode > path = new ArrayList <>();
19
+ while (root != to ) {
20
+ path .add (root );
21
+ if (to .val < root .val ) root = root .left ;
22
+ else root = root .right ;
23
+ }
24
+ path .add (to );
25
+ return path ;
26
+ }
27
+
28
+ private static TreeNode lowestCommonAncestor (List <TreeNode > path1 , List <TreeNode > path2 ) {
29
+ for (int index = 1 ; index < Math .min (path1 .size (), path2 .size ()) ; index ++) {
30
+ if (!path1 .get (index ).equals (path2 .get (index ))) {
31
+ return path1 .get (index - 1 );
32
+ }
33
+ }
34
+ return path1 .get (Math .min (path1 .size (), path2 .size ()) - 1 );
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments