Advertisement
Guest User

Subtree of Another Tree

a guest
Sep 20th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
  2.  
  3.  
  4. +++++++++++++
  5.  
  6.  
  7. class Solution {
  8. public boolean isSubtree(TreeNode s, TreeNode t) {
  9. if(s == null)
  10. return false;
  11. if (isSameTree(s, t))
  12. return true;
  13.  
  14. return isSubtree(s.left,t) || isSubtree(s.right,t);
  15. }
  16.  
  17. public boolean isSameTree(TreeNode s, TreeNode t) {
  18. if(s == null && t == null)
  19. return true;
  20. if(s == null || t == null)
  21. return false;
  22. if(s.val != t.val)
  23. return false;
  24. return isSameTree(s.left,t.left) && isSameTree(s.right,t.right);
  25. }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement