File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @description
3
+ * root tree의 각 노드들에서 subRoot의 root와 같으면 preOrder를 통해 일치하는지 확인하는 로직
4
+ *
5
+ * n = count of root node
6
+ * time complexity: O(n^2)
7
+ * space complexity: O(n^2)
8
+ */
9
+ var isSubtree = function ( root , subRoot ) {
10
+ const findTree = ( tree , target ) => {
11
+ if ( ! tree && ! target ) return true ;
12
+ if ( ! tree || ! target || tree . val !== target . val ) return false ;
13
+
14
+ if ( ! findTree ( tree . left , target . left ) ) return false ;
15
+ if ( ! findTree ( tree . right , target . right ) ) return false ;
16
+
17
+ return true ;
18
+ } ;
19
+
20
+ const preOrder = ( tree ) => {
21
+ if ( ! tree ) return false ;
22
+
23
+ if ( tree . val === subRoot . val ) {
24
+ if ( findTree ( tree , subRoot ) ) return true ;
25
+ }
26
+ if ( preOrder ( tree . left ) ) return true ;
27
+ if ( preOrder ( tree . right ) ) return true ;
28
+
29
+ return false ;
30
+ } ;
31
+
32
+ return preOrder ( root ) ;
33
+ } ;
You can’t perform that action at this time.
0 commit comments