diff --git a/number-of-connected-components-in-an-undirected-graph/hwanmini.js b/number-of-connected-components-in-an-undirected-graph/hwanmini.js new file mode 100644 index 000000000..9735f7f28 --- /dev/null +++ b/number-of-connected-components-in-an-undirected-graph/hwanmini.js @@ -0,0 +1,41 @@ +// V는 정점, E는 간선 +// 시간 복잡도: O(V + E) +// 공간 복잡도: O(V + E) + +class Solution { + /** + * @param {number} n + * @param {number[][]} edges + * @returns {number} + */ + countComponents(n, edges) { + const visited = Array.from({length: n}, () => false); + const graph = new Map(); + + for (const [v, d] of edges) { + if (!graph.has(v)) graph.set(v, []); + if (!graph.has(d)) graph.set(d, []); + + graph.get(v).push(d); + graph.get(d).push(v); + } + + const dfs = (node) => { + visited[node] = true + for (let nei of graph.get(node) || []) { + if (!visited[nei]) dfs(nei) + } + } + + let count = 0; + for (let i = 0; i < n; i++) { + if (!visited[i]) { + dfs(i); + count++; + } + } + + + return count + } +} diff --git a/same-tree/hwanmini.js b/same-tree/hwanmini.js new file mode 100644 index 000000000..50f9e8292 --- /dev/null +++ b/same-tree/hwanmini.js @@ -0,0 +1,23 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function(p, q) { + if ((p && !q) || (!p && q)) return false; + if (!p || !q) return true + if (p.val === q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right) + return false +}; +