Skip to content

Commit 767fa15

Browse files
committed
feat: lowest common ancestor of a binary search tree
1 parent 540540a commit 767fa15

File tree

1 file changed

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

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: ํŠธ๋ฆฌ์˜ ํ•œ์ชฝ ๊ฒฝ๋กœ๋ฅผ ์„ ํƒํ•˜๋ฉด์„œ ํƒ์ƒ‰ํ•˜๋ฏ€๋กœ, ํŠธ๋ฆฌ์˜ ๋†’์ด๊ฐ€ h๋ฉด O(h)
3+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์˜ ๊นŠ์ด๋Š” ๊ท ํ˜• ์žกํžŒ ํŠธ๋ฆฌ์˜ ๊ฒฝ์šฐ O(logn), ํŽธํ–ฅ๋œ ํŠธ๋ฆฌ๋Š” O(n) ==> O(h)
4+
*/
5+
/**
6+
* Definition for a binary tree node.
7+
* function TreeNode(val) {
8+
* this.val = val;
9+
* this.left = this.right = null;
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+
const dfs = (node, p, q) => {
20+
if(node.val > p.val && node.val > q.val) {
21+
return dfs(node.left, p, q);
22+
}
23+
if(node.val < p.val && node.val < q.val) {
24+
return dfs(node.right, p, q);
25+
}
26+
return node;
27+
}
28+
return dfs(root, p, q);
29+
};
30+

0 commit comments

Comments
ย (0)