Skip to content

Commit e354f1d

Browse files
committed
solve: lowest common ancestor of a binary search tree
1 parent 5dcc0f7 commit e354f1d

File tree

1 file changed

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

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* TC: O(logN)
3+
* left와 right 중 한 곳으로만 탐색
4+
*
5+
* SC: O(1)
6+
*/
7+
8+
/**
9+
* Definition for a binary tree node.
10+
* function TreeNode(val) {
11+
* this.val = val;
12+
* this.left = this.right = null;
13+
* }
14+
*/
15+
16+
/**
17+
* @param {TreeNode} root
18+
* @param {TreeNode} p
19+
* @param {TreeNode} q
20+
* @return {TreeNode}
21+
*/
22+
var lowestCommonAncestor = function (root, p, q) {
23+
while (root) {
24+
if (root.val > p.val && root.val > q.val) {
25+
root = root.left;
26+
} else if (root.val < p.val && root.val < q.val) {
27+
root = root.right;
28+
} else {
29+
return root;
30+
}
31+
}
32+
};

0 commit comments

Comments
 (0)