File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +41
-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+ var lowestCommonAncestor = function ( root , p , q ) {
16+ const left = Math . min ( p . val , q . val ) ;
17+ const right = Math . max ( p . val , q . val ) ;
18+
19+ const dfs = ( node ) => {
20+ if ( ! node ) {
21+ return ;
22+ }
23+
24+ if ( node . val >= left && node . val <= right ) {
25+ return node ;
26+ }
27+
28+ if ( node . val > left && node . val > right ) {
29+ return dfs ( node . left ) ;
30+ }
31+
32+ if ( node . val < left && node . val < right ) {
33+ return dfs ( node . right ) ;
34+ }
35+ }
36+
37+ return dfs ( root ) ;
38+ } ;
39+
40+ // ์๊ฐ๋ณต์ก๋ O(logn) -> ์ด์งํธ๋ฆฌ๋ฅผ ์ด์งํ์ํ๋ฉด์ ํธ๋ฆฌ์ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ธฐ๋๋ฌธ(๋์ผํ ๊น์ด์์ ํ ๋ฒ ์ผ์ชฝ์ ๋ฐฉ๋ฌธํ์๋ค๋ฉด, ๊ทธ ๊น์ด์์ ์ค๋ฅธ์ชฝ์ ๋ฐฉ๋ฌธํ์ง ์์)
41+ // ๊ณต๊ฐ๋ณต์ก๋ O(h) -> ์ฌ๊ทํธ์ถ์ ์ฌ์ฉํ์์ผ๋ฏ๋ก ํธ๋ฆฌ์ ๋์ด๋งํผ ์ต๋ ์ฝ์คํ์ ์์์ด ๋ฐ์
You canโt perform that action at this time.
0 commit comments