Skip to content

Commit 33c1b49

Browse files
committed
Add week 13 solutions: lowest-common-ancestor-of-a-binary-search-tree
1 parent 599a7d8 commit 33c1b49

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3+
* time complexity : O(log n)
4+
* space complexity : O(1)
5+
*/
6+
7+
class TreeNode {
8+
val: number
9+
left: TreeNode | null
10+
right: TreeNode | null
11+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
12+
this.val = (val === undefined ? 0 : val)
13+
this.left = (left === undefined ? null : left)
14+
this.right = (right === undefined ? null : right)
15+
}
16+
}
17+
18+
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
19+
while (root) {
20+
if (p.val < root.val && q.val < root.val) root = root.left;
21+
else if (p.val > root.val && q.val > root.val) root = root.right;
22+
else return root;
23+
}
24+
return null;
25+
};

0 commit comments

Comments
 (0)