File tree Expand file tree Collapse file tree 1 file changed +27
-11
lines changed Expand file tree Collapse file tree 1 file changed +27
-11
lines changed Original file line number Diff line number Diff line change 1
- class Solution {
1
+ // Solution: Recursive Approach
2
2
3
+ // Time Complexity: O(n)
4
+ // Extra Space Complexity: O(n)
5
+ class Solution1 {
3
6
public boolean isSubtree (TreeNode root , TreeNode subRoot ) {
4
- if (root == null && subRoot == null ) return true ;
5
- if (root == null || subRoot == null ) return false ;
7
+ if (root == null && subRoot == null ) {
8
+ return true ;
9
+ }
10
+ if (root == null || subRoot == null ) {
11
+ return false ;
12
+ }
13
+ if (isSameTree (root , subRoot )) {
14
+ return true ;
15
+ }
16
+
17
+ return (isSubtree (root .left , subRoot ) || isSubtree (root .right , subRoot ));
18
+ }
19
+
20
+ private boolean isSameTree (TreeNode root , TreeNode subRoot ) {
21
+ if (root == null && subRoot == null ) {
22
+ return true ;
23
+ }
24
+ if (root == null || subRoot == null ) {
25
+ return false ;
26
+ }
6
27
if (root .val == subRoot .val ) {
7
- return (
8
- isSubtree (root .left , subRoot .left ) &&
9
- isSubtree (root .right , subRoot .right )
10
- );
11
- } else {
12
- return (
13
- isSubtree (root .left , subRoot ) || isSubtree (root .right , subRoot )
14
- );
28
+ return (isSameTree (root .left , subRoot .left ) && isSameTree (root .right , subRoot .right ));
15
29
}
30
+
31
+ return false ;
16
32
}
17
33
}
You can’t perform that action at this time.
0 commit comments