-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #607 from Sunjae95/main
[선재] WEEK 15 Solutions
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |