编写代码判断两棵二叉树是否为镜像二叉树
镜像二叉树举例:
a a
b c ==> c b
d d
下面是将一个树转化为镜像二叉树
void swap(struct BiTree** a, struct BiTree** b) //交换将左右子树交换
{
struct BiTree* temp = NULL;
temp = *a;
*a = *b;
*b = temp;
}
struct BiTree* mirrorTree(struct BiTree* root)
{
if (root == NULL)
{
return NULL;
}
if (root->left != NULL) //递归到左子树最深处,
{
root->left = mirrorTree(root->left); //运用递归
}
if (root->right != NULL) //递归到又子树最深处
{
root->right = mirrorTree(root->right);//运用递归
}
swap(&root->left, &root->right);// //将左右节点交换
return root;
}
简洁高效的算法:
一直递归,判断是否相等,递归完左子树再递归右子树
易懂的算法:
struct BiTree
{
int data;
struct BiTree* left;
struct BiTree* right;
};
bool isMirrorTree(struct BiTree* a, struct BiTree* b)
{
if (a == NULL && b == NULL)
{
return true;
}
if (a == NULL && b != NULL)
{
return false;
}
if (a != NULL && b == NULL)
{
return false;
}
if (a->data != b->data)
{
return false;
}
if (a->right != NULL)
{
if (b->left != NULL)
{
if (!isMirrorTree(a->right, b->left))
{
return false;
}
}
else
{
return false;
}
}
if (a->left != NULL)
{
if (b->right != NULL)
{
if (!isMirrorTree(a->left, b->right))
{
return false;
}
}
else
{
return false;
}
}
return true;
}