面试官:这么简单的二叉树算法都不会?
bool isSame(TreeNode* a, TreeNode* b) {
if (a == nullptr && b == nullptr) return true;
else if (a == nullptr || b == nullptr) return false;
else return a->val == b->val && isSame(a->left, b->left) && isSame(a->right, b->right);
}
如果二叉树a和b都为空,那么显然返回true 否则如果a为空或者b为空,那么这两棵树显然不相同,返回false 如果不满足条件1和2,那么如果a和b根节点的值相同并且其左右子树都一样,那么二叉树a和b是相同的二叉树,返回true
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (root == nullptr && subRoot == nullptr) return true;
else if (root == nullptr || subRoot == nullptr) return false;
else return isSame(root, subRoot) || isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
$ md5sum a.c
6004b6a21b274b405a2bd1f1c75a93c7 a.c
void serialize(TreeNode* root, string& str) {
if (root == nullptr) {
str = str + "#";
} else {
str = str + "," + to_string(root->val);
serialize(root->left, str);
serialize(root->right, str);
}
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
string a, b;
serialize(root, a);
serialize(subRoot, b);
return a.find(b)!=string::npos;
}
相关文章