From f4721eecb431b7510ff9017d53375cc996b37e02 Mon Sep 17 00:00:00 2001 From: JEONGHWANMIN Date: Sat, 26 Oct 2024 13:08:56 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=AC=B8=EC=A0=9C=ED=92=80=EC=9D=B4=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- graph-valid-tree/hwanmini.js | 45 ++++++++++++++++++++++++ maximum-depth-of-binary-tree/hwanmini.js | 34 ++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 graph-valid-tree/hwanmini.js create mode 100644 maximum-depth-of-binary-tree/hwanmini.js diff --git a/graph-valid-tree/hwanmini.js b/graph-valid-tree/hwanmini.js new file mode 100644 index 000000000..1afd53142 --- /dev/null +++ b/graph-valid-tree/hwanmini.js @@ -0,0 +1,45 @@ +// V: Node 개수, E: 간선의 개수 +// 시간복잡도: O(V + E) +// 공간복잡도: O(V + E) + +class Solution { + /** + * @param {number} n + * @param {number[][]} edges + * @returns {boolean} + */ + validTree(n, edges) { + const graph = new Map(); + + for (let [u, v] of edges) { + if (!graph.has(u)) graph.set(u, []) + if (!graph.has(v)) graph.set(v, []) + graph.get(u).push(v) + graph.get(v).push(u) + } + + const visited = Array.from({length: n}, () => false); + + let edgeCount = 0; + const queue = [0]; + visited[0] = true + + while(queue.length) { + const cur = queue.shift(); + + for (const edge of graph.get(cur) || []) { + if (!visited[edge]) { + visited[edge] = true; + queue.push(edge) + } + edgeCount++; + } + } + + const isAllVisited = visited.every((visited) => visited === true) + + return isAllVisited && (edgeCount / 2) === (n - 1) + } + + +} diff --git a/maximum-depth-of-binary-tree/hwanmini.js b/maximum-depth-of-binary-tree/hwanmini.js new file mode 100644 index 000000000..96981c0ea --- /dev/null +++ b/maximum-depth-of-binary-tree/hwanmini.js @@ -0,0 +1,34 @@ +// 시간복잡도: 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} root + * @return {number} + */ +var maxDepth = function(root) { + if (!root) return 0; + + let maxDepth = 0; + const exploreMaxDepth = (node, depth) => { + if (!node) { + maxDepth = Math.max(maxDepth, depth) + return + } + + + exploreMaxDepth(node.left, depth + 1) + exploreMaxDepth(node.right, depth + 1) + } + + exploreMaxDepth(root, 0) + + return maxDepth +};