Skip to content

Commit b998871

Browse files
committed
lowest common ancestor of a binary search tree solution
1 parent 130fa32 commit b998871

File tree

1 file changed

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

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// 시간복잡도: 이진검색트리가 균형잡힌 경우 O(logN), 균형잡히지 않은 경우 O(N)
2+
// 공간복잡도: O(1)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val) {
7+
* this.val = val;
8+
* this.left = this.right = null;
9+
* }
10+
*/
11+
12+
/**
13+
* @param {TreeNode} root
14+
* @param {TreeNode} p
15+
* @param {TreeNode} q
16+
* @return {TreeNode}
17+
*/
18+
var lowestCommonAncestor = function(root, p, q) {
19+
while(root) {
20+
// root의 값보다 p와 q의 값이 모두 작으면 root를 root.left로 이동
21+
if (p.val < root.val && q.val < root.val) {
22+
root = root.left;
23+
}
24+
// root의 값보다 p와 q의 값이 모두 크면 root를 root.right로 이동
25+
else if (p.val > root.val && q.val > root.val) {
26+
root = root.right;
27+
}
28+
else break;
29+
}
30+
return root;
31+
};

0 commit comments

Comments
 (0)