Advertisement
Guest User

task5

a guest
Aug 25th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.61 KB | None | 0 0
  1. // n - count of nodes in tree `s`,
  2. // m - count of nodes in tree `t`.
  3. // O(n * m) - time complexity,
  4. // O(n) - space complexity.
  5. class Solution {
  6.     public boolean isSubtree(TreeNode s, TreeNode t) {
  7.         return s != null && (isEquals(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t));
  8.     }
  9.    
  10.     private boolean isEquals(TreeNode s, TreeNode t) {
  11.         if (s == null && t == null) {
  12.             return true;
  13.         }
  14.         if (s == null || t == null) {
  15.             return false;
  16.         }
  17.         return s.val == t.val && isEquals(s.left, t.left) && isEquals(s.right, t.right);
  18.     }
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement