File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3
+ * Definition for a binary tree node.
4
+ * function TreeNode(val) {
5
+ * this.val = val;
6
+ * this.left = this.right = null;
7
+ * }
8
+ */
9
+
10
+ /**
11
+ * @param {TreeNode } root
12
+ * @param {TreeNode } p
13
+ * @param {TreeNode } q
14
+ * @return {TreeNode }
15
+ */
16
+ var lowestCommonAncestor = function ( root , p , q ) {
17
+ let current = root ;
18
+
19
+ while ( current ) {
20
+ // ๋ ๋
ธ๋์ ๊ฐ์ด ํ์ฌ ๋
ธ๋๋ณด๋ค ๋ชจ๋ ์์ผ๋ฉด ์ผ์ชฝ ์๋ธํธ๋ฆฌ๋ก ์ด๋
21
+ if ( p . val < current . val && q . val < current . val ) {
22
+ current = current . left ;
23
+ }
24
+ // ๋ ๋
ธ๋์ ๊ฐ์ด ํ์ฌ ๋
ธ๋๋ณด๋ค ๋ชจ๋ ํฌ๋ฉด ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ก ์ด๋
25
+ else if ( p . val > current . val && q . val > current . val ) {
26
+ current = current . right ;
27
+ }
28
+ // ํ์ฌ ๋
ธ๋๊ฐ ๋ถ๊ธฐ์ ์ด๋ฉด ๊ทธ๊ฒ LCA!
29
+ else {
30
+ return current ;
31
+ }
32
+ }
33
+
34
+ return null ; // ๋ง์ฝ ํธ๋ฆฌ์ ์๋ค๋ฉด null ๋ฐํ (์ผ๋ฐ์ ์ผ๋ก BST์๋ ํญ์ ์กด์ฌํ๋ค๊ณ ๊ฐ์ )
35
+ } ;
You canโt perform that action at this time.
0 commit comments