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);