1
+ // Check if a binary tree is subtree of another binary tree
2
+ // Root of the source tree and the tree to be matched are provided in the parameters.
3
+ // Return true/false based on whether or not the given tree is the subtree of the source tree
4
+ // Time complexity : O(m*n) m is the number of nodes of the original tree,
5
+ // n is the number of nodes in the tree to be matched
6
+
7
+ function areIdentical ( rootOfOriginalTree , rootOfMatchingTree ) {
8
+ if ( rootOfOriginalTree === null && rootOfMatchingTree === null ) {
9
+ return true ;
10
+ }
11
+
12
+ if ( rootOfOriginalTree === null || rootOfMatchingTree === null ) {
13
+ return false ;
14
+ }
15
+
16
+ return ( rootOfOriginalTree . value === rootOfMatchingTree . value ) && areIdentical ( rootOfOriginalTree . leftChild , rootOfMatchingTree . leftChild ) && areIdentical ( rootOfOriginalTree . rightChild , rootOfMatchingTree . rightChild ) ;
17
+ }
18
+
19
+ function isSubtree ( rootOfOriginalTree , rootOfMatchingTree ) {
20
+ if ( rootOfMatchingTree === null ) {
21
+ return true ;
22
+ }
23
+
24
+ if ( rootOfOriginalTree === null ) {
25
+ return false ;
26
+ }
27
+
28
+ if ( areIdentical ( rootOfOriginalTree , rootOfMatchingTree ) ) {
29
+ return true ;
30
+ }
31
+
32
+ return isSubtree ( rootOfOriginalTree . leftChild , rootOfMatchingTree ) || isSubtree ( rootOfMatchingTree . rightChild , rootOfMatchingTree ) ;
33
+ }
34
+
35
+ module . exports = {
36
+ isSubtree,
37
+ } ;
0 commit comments