Skip to content

Commit fe056ca

Browse files
committed
feat: lowest-common-ancestor-of-a-binary-search-tree
1 parent d198ece commit fe056ca

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">week13-2. lowest-common-ancestor-of-a-binary-search-tree</a>
3+
* <li>Description: find the lowest common ancestor (LCA) node of two given nodes in the BST. </li>
4+
* <li>Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree </li>
5+
* <li>Time Complexity: O(H), Runtime 5ms </li>
6+
* <li>Space Complexity: O(1), Memory 44.91MB </li>
7+
*/
8+
9+
class Solution {
10+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
11+
TreeNode node = root;
12+
while (node != null) {
13+
if (p.val < node.val && q.val < node.val) {
14+
node = node.left;
15+
} else if (p.val > node.val && q.val > node.val) {
16+
node = node.right;
17+
} else {
18+
return node;
19+
}
20+
}
21+
22+
throw new IllegalArgumentException();
23+
}
24+
}

0 commit comments

Comments
 (0)