Skip to content

Commit 4d6131c

Browse files
solves lowest cmmon ancestor
1 parent b2f7394 commit 4d6131c

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https://github.com/anishLearnsToCode/leetcode-algorithms)
44
![made-with-java](https://img.shields.io/badge/Made%20with-Java-1f425f.svg)
55
![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)
88
![problems-solved-python](https://img.shields.io/badge/Python-3/1412-1abc9c.svg)
99
[![license](https://img.shields.io/badge/LICENSE-MIT-<COLOR>.svg)](LICENSE)
1010
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)