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.
递归实现,代码有点美😄
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSametree(struct TreeNode*s,struct TreeNode* t)
{
if(NULL== s && NULL == t)
return true;
if(NULL== s || NULL == t)
return false;
if(s->val != t->val)
return false;
return isSametree(s->left,t->left) && isSametree(s->right,t->right);
}
bool isSubtree(struct TreeNode* s, struct TreeNode* t)
{
if(NULL == s)
return false;
if(isSametree(s,t))
return true;
return isSubtree(s->left,t) ||isSubtree(s->right,t);
}