给定两个非空二叉树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 isSubtree(TreeNode * s, TreeNode * t) {
// Write your code here
if(s==NULL) return false;
if(s->val==t->val&&isIdentical(s,t)) return true;
return isSubtree(s->left,t)||isSubtree(s->right,t);
}
bool isIdentical(TreeNode * a, TreeNode * b) {
// write your code here
if(a==NULL&&b==NULL) return true;
if(a == NULL && b != NULL || a!= NULL && b == NULL || a->val != b->val) return false;
return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right);
}
};