SHARE
TWEET

task5

a guest Aug 25th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top