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.
Example 1:
Given tree s:
3
/
4 5
/
1 2
Given tree t:
4
/
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/
4 5
/
1 2
/
0
Given tree t:
4
/
1 2
Return false.
判断树s是否包含树t
C++(29ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSubtree(TreeNode* s, TreeNode* t) { 13 if (s == NULL) 14 return false ; 15 if (isSame(s,t)) 16 return true ; 17 return isSubtree(s->left , t) || isSubtree(s->right , t) ; 18 } 19 20 bool isSame(TreeNode* s, TreeNode* t){ 21 if (s == NULL && t == NULL) 22 return true ; 23 if (s == NULL || t == NULL) 24 return false ; 25 if (s->val != t->val) 26 return false ; 27 return isSame(s->left , t->left) && isSame(s->right , t->right) ; 28 } 29 };