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