Skip to content

Commit bff7a01

Browse files
committed
Add week 7 solutions : lowestCommonAncestorOfABinarySearchTree
1 parent f42bd6e commit bff7a01

File tree

1 file changed

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

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
var lowestCommonAncestor = function (root, p, q) {
5+
// start from the root.
6+
let current = root;
7+
8+
// traverse the tree.
9+
while (current !== null) {
10+
// if both p and q are greater than current node, LCA lies in the right.
11+
if (p.val > current.val && q.val > current.val) {
12+
current = current.right;
13+
}
14+
// if both p and q are smaller than current node, LCA lies in the left.
15+
else if (p.val < current.val && q.val < current.val) {
16+
current = current.left;
17+
}
18+
// if one of p or q is on one side and the other is on the other side, It's LCA.
19+
else {
20+
return current;
21+
}
22+
}
23+
24+
// if the tree is empty.
25+
return null;
26+
};

0 commit comments

Comments
 (0)