File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @param {TreeNode } subRoot
12
+ * @return {boolean }
13
+ */
14
+ const isSubtree = function ( root , subRoot ) {
15
+ const isSame = function ( node1 , node2 ) {
16
+ if ( ! node1 && ! node2 ) return true ;
17
+ if ( node1 ?. val !== node2 ?. val ) return false ;
18
+
19
+ return isSame ( node1 . left , node2 . left ) && isSame ( node1 . right , node2 . right ) ;
20
+ }
21
+
22
+ const queue = [ root ] ;
23
+
24
+ while ( queue . length ) {
25
+ const node = queue . shift ( ) ;
26
+
27
+ if ( node . left ) {
28
+ queue . push ( node . left ) ;
29
+ }
30
+
31
+ if ( node . right ) {
32
+ queue . push ( node . right ) ;
33
+ }
34
+
35
+ if ( isSame ( node , subRoot ) ) {
36
+ return true ;
37
+ }
38
+ }
39
+
40
+ return false ;
41
+ } ;
42
+
43
+ // ๋ค๋ฅธ ์ ๊ทผ๋ฒ:
44
+ // ์ ๋ ฌํด์ ๋น๊ตํ๋ ๋ฐฉ์ => left, right ๊ตฌ๋ถ์ด ์๊ฐ๋ ๋ฌธ์
45
+ // ์ ๋ ฌํ ๋ left, right ์ ๋ณด๋ฅผ ํฌํจํด์ ์ง๋ ฌํํ๋ฉด ๋จ
46
+ // ์ด๋ ๊ฒ ํ๋ฉด ๋ณต์ก๋ ๋ฉด์์ ์ฑ๋ฅ์ด ๋ ์ข์
47
+
48
+ // ์๊ฐ๋ณต์ก๋: O(n * m) (n: root size, m: subroot size)
49
+ // ๊ณต๊ฐ๋ณต์ก๋: O(n + m)
You canโt perform that action at this time.
0 commit comments