Skip to content

Commit 96c50c3

Browse files
committed
lowest common ancestor of a binary search tree solution
1 parent 71d2d0e commit 96c50c3

File tree

1 file changed

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

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+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*
14+
* Time Complexity: O(h) where h is the height of the tree
15+
* Space Complexity: O(1)
16+
*/
17+
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
18+
if (p.val < root.val && q.val < root.val) {
19+
return lowestCommonAncestor(root.left, p, q);
20+
} else if (p.val > root.val && q.val > root.val) {
21+
return lowestCommonAncestor(root.right, p, q);
22+
}
23+
24+
return root;
25+
}

0 commit comments

Comments
 (0)