From f5a2f9233bd8f1712d61aea2e9a75836fb91f4be Mon Sep 17 00:00:00 2001 From: JiHo00 <110150963+jihostudy@users.noreply.github.com> Date: Fri, 19 Jul 2024 21:20:25 +0900 Subject: [PATCH] =?UTF-8?q?Day19=202Q=20=EC=A7=80=ED=98=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Leetcode_572. Subtree of Another Tree.js | 15 ++++++++ ...24\354\235\264\353\237\254\354\212\244.js" | 38 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 Jiho/Day19/Leetcode_572. Subtree of Another Tree.js create mode 100644 "Jiho/Day19/\353\260\261\354\244\200_2606_\353\260\224\354\235\264\353\237\254\354\212\244.js" diff --git a/Jiho/Day19/Leetcode_572. Subtree of Another Tree.js b/Jiho/Day19/Leetcode_572. Subtree of Another Tree.js new file mode 100644 index 0000000..40ebf75 --- /dev/null +++ b/Jiho/Day19/Leetcode_572. Subtree of Another Tree.js @@ -0,0 +1,15 @@ +const isSubtree = (root, subRoot) => { + const areEqual = (node1, node2) => { + if (!node1 || !node2) return !node1 && !node2; + if (node1.val !== node2.val) return false; + return ( + areEqual(node1.left, node2.left) && areEqual(node1.right, node2.right) + ); + }; + const dfs = (node) => { + if (!node) return false; + if (areEqual(node, subRoot)) return true; + return dfs(node.left) || dfs(node.right); + }; + return dfs(root); +}; diff --git "a/Jiho/Day19/\353\260\261\354\244\200_2606_\353\260\224\354\235\264\353\237\254\354\212\244.js" "b/Jiho/Day19/\353\260\261\354\244\200_2606_\353\260\224\354\235\264\353\237\254\354\212\244.js" new file mode 100644 index 0000000..15808bf --- /dev/null +++ "b/Jiho/Day19/\353\260\261\354\244\200_2606_\353\260\224\354\235\264\353\237\254\354\212\244.js" @@ -0,0 +1,38 @@ +const fs = require("fs"); +const input = fs + .readFileSync(process.platform === "linux" ? "/dev/stdin" : "../input.txt") + .toString() + .trim() + .split("\n"); + +const [N, M, ...connectionsArr] = input; +const numOfDesktop = parseInt(N); +const numOfConnections = parseInt(M); +const connections = connectionsArr.map((elm) => + elm.trim().split(" ").map(Number) +); +const graph = Array.from(Array(numOfDesktop + 1), () => new Array()); + +for (const [l, r] of connections) { + graph[l].push(r); + graph[r].push(l); +} + +// Using Stack dfs +let answer = 0; + +const stack = [1]; +const visited = new Array(numOfDesktop + 1).fill(false); +visited[1] = true; +while (stack.length) { + const target = stack.pop(); + answer += 1; + // push values connected to val while not visited + for (const val of graph[target]) { + if (!visited[val]) { + stack.push(val); + visited[val] = true; + } + } +} +console.log(answer - 1);