Skip to content

Commit aab9310

Browse files
Jeehay28Jeehay28
authored andcommitted
Add LSA of BST solution in TS
1 parent b70bf18 commit aab9310

File tree

1 file changed

+53
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
// TC: O(n)
13+
// SC: O(1)
14+
function lowestCommonAncestor(
15+
root: TreeNode | null,
16+
p: TreeNode | null,
17+
q: TreeNode | null
18+
): TreeNode | null {
19+
if (!root || !p || !q) return null;
20+
21+
let node = root;
22+
23+
while (node) {
24+
if (node.val < p.val && node.val < q.val) {
25+
node = node.right!;
26+
} else if (node.val > p.val && node.val > q.val) {
27+
node = node.left!;
28+
} else {
29+
return node;
30+
}
31+
}
32+
33+
return null;
34+
}
35+
36+
37+
// TC: O(n)
38+
// SC: O(n)
39+
// function lowestCommonAncestor(
40+
// root: TreeNode | null,
41+
// p: TreeNode | null,
42+
// q: TreeNode | null
43+
// ): TreeNode | null {
44+
// if (!root || !p || !q) return null;
45+
46+
// if (p.val < root.val && q.val < root.val) {
47+
// return lowestCommonAncestor(root.left, p, q);
48+
// } else if (p.val > root.val && q.val > root.val) {
49+
// return lowestCommonAncestor(root.right, p, q);
50+
// } else {
51+
// return root;
52+
// }
53+
// }

0 commit comments

Comments
 (0)