File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 풀이
3+ - 두 트리가 동일한지 검사하는 dfs 함수를 이용하여 풀이할 수 있습니다
4+ Big O
5+ - M: root 트리의 노드 개수
6+ - N: subRoot 트리의 노드 개수
7+ - Time complexity: O(MN)
8+ - 최악의 경우 root 트리의 모든 노드에 대해 isSameTree 함수를 실행 (O(M))
9+ 최악의 경우 isSameTree 함수는 O(N)의 시간복잡도를 가짐
10+ - Space complexity: O(M+N)
11+ - isSubTree의 재귀호출스택 깊이는 최대 O(M)의 공간복잡도를 가짐
12+ - isSameTree의 재귀호출스택 깊이는 최대 O(N)의 공간복잡도를 가짐
13+ */
14+
15+ /**
16+ * Definition for a binary tree node.
17+ * type TreeNode struct {
18+ * Val int
19+ * Left *TreeNode
20+ * Right *TreeNode
21+ * }
22+ */
23+ func isSubtree (root * TreeNode , subRoot * TreeNode ) bool {
24+ // handling nil(null) inputs
25+ if root == nil {
26+ return false
27+ }
28+ // return true if root and subroot are same
29+ if isSameTree (root , subRoot ) {
30+ return true
31+ }
32+ // else, check root.left and root.right
33+ return isSubtree (root .Left , subRoot ) || isSubtree (root .Right , subRoot )
34+ }
35+
36+ /*
37+ dfs helper function checking whether two treenodes are same or not
38+ */
39+ func isSameTree (a * TreeNode , b * TreeNode ) bool {
40+ // handling nil(null) cases
41+ if a == nil || b == nil {
42+ return a == b
43+ }
44+ // falsy cases
45+ if a .Val != b .Val || ! isSameTree (a .Left , b .Left ) || ! isSameTree (a .Right , b .Right ) {
46+ return false
47+ }
48+ // else, return true
49+ return true
50+ }
You can’t perform that action at this time.
0 commit comments