From bb99027bf35bf0b3f14ad77ce756692e82078b27 Mon Sep 17 00:00:00 2001 From: SeonjaeLee Date: Wed, 20 Nov 2024 15:00:45 +0900 Subject: [PATCH] 1. Subtree of Another Tree --- subtree-of-another-tree/sunjae95.js | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 subtree-of-another-tree/sunjae95.js diff --git a/subtree-of-another-tree/sunjae95.js b/subtree-of-another-tree/sunjae95.js new file mode 100644 index 000000000..4446444d3 --- /dev/null +++ b/subtree-of-another-tree/sunjae95.js @@ -0,0 +1,33 @@ +/** + * @description + * root tree의 각 노드들에서 subRoot의 root와 같으면 preOrder를 통해 일치하는지 확인하는 로직 + * + * n = count of root node + * time complexity: O(n^2) + * space complexity: O(n^2) + */ +var isSubtree = function (root, subRoot) { + const findTree = (tree, target) => { + if (!tree && !target) return true; + if (!tree || !target || tree.val !== target.val) return false; + + if (!findTree(tree.left, target.left)) return false; + if (!findTree(tree.right, target.right)) return false; + + return true; + }; + + const preOrder = (tree) => { + if (!tree) return false; + + if (tree.val === subRoot.val) { + if (findTree(tree, subRoot)) return true; + } + if (preOrder(tree.left)) return true; + if (preOrder(tree.right)) return true; + + return false; + }; + + return preOrder(root); +};