Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[선재] WEEK 15 Solutions #607

Merged
merged 1 commit into from
Nov 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Comment on lines +6 to +7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 시간 복잡도는 root의 노드 수인 n, subTree의 노드 수인 m으로 뒀을 때
최악의 경우 n과 m의 노드를 모두 비교해야 해서 O(n * m) 으로,
공간 복잡도의 경우 각 트리의 높이를 h1, h2로 두고
O(h1 +h2)가 소요될것 같은데 의견 부탁드립니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아이고 제가 코멘트를 볼 시간이 없어서 바보같은 질문을 했네요.
이 부분은 스터디에서 소통했기에 스킵하겠습니다!

*/
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;
Comment on lines +14 to +17
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return findTree(tree.left, target.left) || findTree(tree.right, target,right);
으로 바꾸면 둘 중 하나면 false라도 false가 반환 될테니 짧게 줄일 수 있을것 같아요.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or연산자를 사용하면 피연산자가 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;
Comment on lines +26 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return preOrder(tree.left) && preOrder(tree.right)
으로 바꾸면 subTree는 무조건 양쪽 모두 값이 같아야 하니 코드를 줄일 수 있을것 같습니다.

};

return preOrder(root);
};