https://leetcode.com/problems/subtree-of-another-tree

1. Use recursion:

  1. //28 ms 18.5 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. bool isSubtree(TreeNode* s, TreeNode* t) {
  14. if(!s) return false;
  15. bool isSub = false;
  16. bool isSubL = isSubtree(s->left, t);
  17. bool isSubR = isSubtree(s->right, t);
  18. if(s->val == t->val)
  19. isSub = isSameTree(s, t);
  20. return isSub || isSubL || isSubR;
  21. }
  22. private:
  23. bool isSameTree(TreeNode* s, TreeNode* t) {
  24. if(!s && !t) return true;
  25. else if((!s && t) || (s && !t)) return false;
  26. bool isSubL = isSameTree(s->left, t->left);
  27. bool isSubR = isSameTree(s->right, t->right);
  28. if(s->val == t->val)
  29. return isSubL && isSubR;
  30. else
  31. return false;
  32. }
  33. };