Skip to content

Commit cfe38a9

Browse files
committed
solve: lowest common ancestor of a BST
1 parent 5e53d5f commit cfe38a9

File tree

1 file changed

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

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @param {TreeNode} p
11+
* @param {TreeNode} q
12+
* @return {TreeNode}
13+
*/
14+
var lowestCommonAncestor = function (root, p, q) {
15+
if (root.val < p.val && root.val < q.val) {
16+
return lowestCommonAncestor(root.right, p, q);
17+
}
18+
19+
if (root.val > p.val && root.val > q.val) {
20+
return lowestCommonAncestor(root.left, p, q);
21+
}
22+
23+
return root;
24+
};
25+
26+
/**
27+
* Time Complexity: O(h), where h is the height of the binary search tree.
28+
* Space Complexity: O(h), where h is the height of the binary search tree.
29+
*/

0 commit comments

Comments
 (0)