Skip to content

Commit

Permalink
Merge pull request #607 from Sunjae95/main
Browse files Browse the repository at this point in the history
[선재] WEEK 15 Solutions
  • Loading branch information
Sunjae95 authored Nov 24, 2024
2 parents 010dc6d + bb99027 commit c19b630
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions subtree-of-another-tree/sunjae95.js
Original file line number Diff line number Diff line change
@@ -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);
};

0 comments on commit c19b630

Please sign in to comment.