Skip to content
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
29 changes: 29 additions & 0 deletions subtree-of-another-tree/Lustellz.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Runtime: 8ms
// Memory: 63.23MB

/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/

const isSameTree = (p, q): boolean => {
if (!(p && q)) return p === q
Copy link
Contributor

Choose a reason for hiding this comment

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

이렇게 코드 한 줄로도 pq 중 하나라도 null일 때 둘다 null이면 true를, 하나만 null이면 false를 반환하는 동작을 처리할 수 있군요!

제가 이 문제를 풀 당시에는 해당 조건을 분기문을 다 나누어서 작성했었는데 덕분에 배워갑니다 ><

if (p.val !== q.val) return false
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}

function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
if (!subRoot) return true
if (!root) return false
if (isSameTree(root, subRoot)) return true
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
};