You have two every large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
1.
利用BFS 搜索到第一个node 与T2 的root相同,然后进行判断这两个子树是否相同---错误,可能存在多个相同值的node
2.
无非进行多次判断,有三种可能情况 1. 判断当前node为root的子树和T2是否相同 2. root 左子树和T2 3. T2 右子树 和T2
class Solution {
public:
/**
* @param T1, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
bool isSubtree(TreeNode *T1, TreeNode *T2) {
// write your code here
if(T2 == NULL){
return true;
}
else if(T1 == NULL){
return false;
}
else{
return isSameTree(T1, T2) || isSubtree(T1->left,T2) || isSubtree(T1->right, T2);
}
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL){
return true;
}
else if(p==NULL){
return false;
}
else if(q==NULL){
return false;
}
else{
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)&&(p->val==q->val);
}
}