给定两个非空二叉树s和t,检查树t是否和树s的一个子树具有完全相同的结构和节点值。 s的子树是一个由s中的一个节点和该节点的后续组成的树。 树s本身也可以被视为自己的一个子树。
样例
样例1:
给出树s:
3
/ \
4 5
/ \
1 2
给出树t:
4
/ \
1 2
返回true,因为t和s的子树具有完全相同的结构和节点值。
样例2:
给出树s:
3
/ \
4 5
/ \
1 2
/
0
给出树t:
4
/ \
1 2
返回false.
输入测试数据 (每行一个参数)如何理解测试数据?
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param s: the s' root
* @param t: the t' root
* @return: whether tree t has exactly the same structure and node values with a subtree of s
*/
bool ret;
bool isSubtree(TreeNode * s, TreeNode * t)
{
// Write your code here
ret = false;
bianli(s,t);
return ret;
}
void bianli(TreeNode * s, TreeNode * t)
{
if(s != NULL)
{
if(isequal(s,t))
{
ret = true;
}
bianli(s->left, t);
bianli(s->right, t);
}
}
bool isequal(TreeNode * s, TreeNode * t)
{
if(s == NULL && t == NULL)
return true;
if(s == NULL || t == NULL)
return false;
if(s->val != t->val)
return false;
return isequal(s->left,t->left) && isequal(s->right,t->right);
}
};