您的位置:首页 > 其它

判断tl树中是否有与t2树拓扑结构完全相同的子树

2016-12-09 21:50 459 查看
两棵彼此独立的二叉树A和B,请编写一个高效算法,检查A中是否存在一棵子树与B树的拓扑结构完全相同。

给定两棵二叉树的头结点A和B,请返回一个bool值,代表A中是否存在一棵同构于B的子树。

【解析】把树转化成字符串,用KMP即可。

代码如下:

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/

class IdenticalTree {
public:
bool chkIdentical(TreeNode* A, TreeNode* B) {
if(A == NULL || B == NULL)
return false;
std::string sa = serialize_tree(A);
std::string sb = serialize_tree(B);
return KMP(sa.c_str(), sb.c_str(), sa.length(), sb.length()) != -1;
}
private:
std::string serialize_tree(TreeNode* t){
if(t == NULL)
return std::string("#!"); //都要转化为string类型,所以是双引号,而不是单引号
std::string res = std::to_string(t->val) + "!"; //数字转化字符串使用to_string即可
res += serialize_tree(t->left);
res += serialize_tree(t->right);
return res;
}
int KMP(const char* S, const char* L, const int len_s, const int len_l){
std::vector<int> next = get_next(L, len_l);
int i = 0, j = 0;
while(i < len_s && j < len_l){
if(j == -1 || S[i] == L[j]){
++i;
++j;
}
else
j = next[j];
}
return j == len_l ? i - j : -1; //(1)注意是判断j,不是i
}
std::vector<int> get_next(const char* L, const int len){
vector<int> next(len);
next[0] = -1;
int j = 0, k = -1;
while(j < len - 1){ //(2)注意是j<len-1不是j<len
if(k == -1 || L[k] == L[j])
next[++j] = ++k;
else
k = next[k];
}
return next;
}
};

KMP好久没用了,有两点给写错了,就是注释中的(1)(2)两点,浪费我好一段时间,还有就是数字转化字符串可以使用std::to_string()函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: