前言
什么是二叉树镜像
其实就是左右子树对调一下就是二叉树的镜像了
比如下面两图就是互为镜像的二叉树
递归方法
方法分析
采用分置的思想,大事化小事,把交换左右子树地址的事交给每一个栈帧完成。
完整代码
//二叉树的镜像 递归方法
void BTreeMirrorR(BTNode* root)
{
BTNode* tmp;
if (root == NULL)
return;
BTreeMirrorR(root->_left);
BTreeMirrorR(root->_right);
tmp = root->_left;
root->_left = root->_right;
root->_right = tmp;
}
非递归方法
方法分析
可以在层序遍历的基础上对每一层的结点的左右子树进行交换
//二叉树的镜像 非递归方法
void BTreeMirror(BTNode* root)
{
BTNode* top;
BTNode* tmp;
Queue Q;
if (root == NULL)
return;
QueueInit(&Q);
QueuePush(&Q, root);
while (!QueueEmpty(&Q))
{
top = QueueFront(&Q);
if (top->_left != NULL)
QueuePush(&Q,top->_left);
if (top->_right != NULL)
QueuePush(&Q, top->_right);
//交换左右子树的地址
tmp = top->_left;
top->_left = top->_right;
top->_right = tmp;
QueuePop(&Q);
}
}