File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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
+ /**
10
+ * @param {TreeNode } root
11
+ * @param {TreeNode } p
12
+ * @param {TreeNode } q
13
+ * @return {TreeNode }
14
+ */
15
+ const lowestCommonAncestor = function ( root , p , q ) {
16
+ // ์ด์งํ์ํธ๋ฆฌ(BST)์ ํน์ง์ ํ์ฉํ์ฌ
17
+ // p, q์ ๊ฐ๊ณผ root ๊ฐ์ ๋น๊ตํด p, q๊ฐ ์ํ ํธ๋ฆฌ(left/right)๋ฅผ ํ๋จ
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
+ } else {
23
+ return root ;
24
+ }
25
+ } ;
26
+
27
+ // ์๊ฐ๋ณต์ก๋: O(h) (h: ํธ๋ฆฌ์ ๋์ด, ์ฆ ์ฌ๊ท ์คํ ๊น์ด)
28
+ // ๊ณต๊ฐ๋ณต์ก๋: O(h) (h: ํธ๋ฆฌ์ ๋์ด, ์ฆ ์ฌ๊ท ์คํ ๊น์ด)
You canโt perform that action at this time.
0 commit comments