|
| 1 | +/** |
| 2 | + * Source: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree |
| 3 | + * Solution: DFS๋ฅผ ์ด์ฉํด์ ๋ ๋
ธ๋๊น์ง์ ๊ฒฝ๋ก๋ฅผ ๊ตฌํด ์์ฐจ์ ์ผ๋ก ๋น๊ตํ๋ฉด์ ๊ฐ์ฅ ๋ง์ง๋ง ๋์ผ ๋
ธ๋๋ฅผ ์ถ์ถ |
| 4 | + * |
| 5 | + * ์๊ฐ๋ณต์ก๋: O(N) - ์ต์
์ธ ๊ฒฝ์ฐ, ์ ์ฒด ๋
ธ๋์ ํ์ |
| 6 | + * ๊ณต๊ฐ๋ณต์ก๋: O(N) - ์ต์
์ธ ๊ฒฝ์ฐ, ์ ์ฒด ๋
ธ๋์ ๋ณด๊ด |
| 7 | + * |
| 8 | + * ๋ค๋ฅธ ํ์ด |
| 9 | + * - ์ฌ๊ท๋ก๋ ํด๊ฒฐํ ๊ฒ์ผ๋ก ๋ณด์ด์ง๋ง ๋ฐ๋ก ๊ตฌํ์ฒด๊ฐ ๋ ์ค๋ฅด์ง ์์ |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Definition for a binary tree node. |
| 14 | + * class TreeNode { |
| 15 | + * val: number |
| 16 | + * left: TreeNode | null |
| 17 | + * right: TreeNode | null |
| 18 | + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 19 | + * this.val = (val===undefined ? 0 : val) |
| 20 | + * this.left = (left===undefined ? null : left) |
| 21 | + * this.right = (right===undefined ? null : right) |
| 22 | + * } |
| 23 | + * } |
| 24 | + */ |
| 25 | + |
| 26 | +function lowestCommonAncestor( |
| 27 | + root: TreeNode | null, |
| 28 | + p: TreeNode | null, |
| 29 | + q: TreeNode | null |
| 30 | +): TreeNode | null { |
| 31 | + if (!root || !p || !q) return null; |
| 32 | + let stack = new Array(root); |
| 33 | + let pRoute: Array<TreeNode> | null; |
| 34 | + let qRoute: Array<TreeNode> | null; |
| 35 | + let answer: TreeNode | null; |
| 36 | + const visited = new Set(); |
| 37 | + |
| 38 | + while (stack.length) { |
| 39 | + const left = stack.at(-1).left; |
| 40 | + if (left && !visited.has(left.val)) { |
| 41 | + stack.push(left); |
| 42 | + continue; |
| 43 | + } |
| 44 | + const right = stack.at(-1).right; |
| 45 | + if (right && !visited.has(right.val)) { |
| 46 | + stack.push(right); |
| 47 | + continue; |
| 48 | + } |
| 49 | + const now = stack.pop(); |
| 50 | + visited.add(now.val); |
| 51 | + if (now.val === q.val) { |
| 52 | + qRoute = [...stack, now]; |
| 53 | + continue; |
| 54 | + } |
| 55 | + if (now.val === p.val) { |
| 56 | + pRoute = [...stack, now]; |
| 57 | + continue; |
| 58 | + } |
| 59 | + } |
| 60 | + const shortLength = |
| 61 | + pRoute.length > qRoute.length ? qRoute.length : pRoute.length; |
| 62 | + for (let i = 0; i < shortLength; i++) { |
| 63 | + if (pRoute.at(i) !== qRoute.at(i)) { |
| 64 | + answer = pRoute.at(i - 1); |
| 65 | + break; |
| 66 | + } |
| 67 | + } |
| 68 | + return answer ? answer : pRoute.at(shortLength - 1); |
| 69 | +} |
0 commit comments