You have two very 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.
参考:http://blog.csdn.net/fightforyourdream/article/details/20446739
其中有2个递归,isSubTree遍历递归来找到子树,这个过程需要每次判断当前t1中的当前子树是否和t2相同,也就是isSameTree递归。
时间复杂度O(mn)
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *createTree(int *num, int left, int right)
{
if (left > right)
return NULL;
int mid = (left + right) / 2;
TreeNode *node = new TreeNode(num[mid]);
node->left = createTree(num, left, mid - 1);
node->right = createTree(num, mid + 1, right);
return node;
}
TreeNode *sortedArrayToBST(int *num, int size)
{
createTree(num, 0, size - 1);
}
//=================================
bool isSameTree(TreeNode *t1, TreeNode *t2)
{
if(t1==NULL && t2==NULL)
return true;
if(t1==NULL || t2==NULL)
return false;
if(t1->val!=t2->val)
return false;
return isSameTree(t1->left, t2->left) && isSameTree(t1->right, t2->right);
}
bool isSubTree(TreeNode *t1, TreeNode *t2)
{
if(t2==NULL)
return true;
if(t1==NULL)
return false;
if(t1->val==t2->val)
if(isSameTree(t1, t2))
return true;
return isSubTree(t1->left, t2) || isSubTree(t1->right, t2);
}
int main()
{
int num1[]= {1,2,3,4,5,6,7,8,9};
TreeNode *root1 = sortedArrayToBST(num1,9);
int num2[]= {6,7,8,9};
TreeNode *root2 = sortedArrayToBST(num2,4);
int num3[]= {3,4};
TreeNode *root3 = sortedArrayToBST(num3,2);
cout<<isSubTree(root1, root2)<<endl;
cout<<isSubTree(root1, root3)<<endl;
return 0;
}