问题:
求一颗树的镜向
解决思路:
镜向其实就是将所有结点的左右两个子结点交换就行。所以可以遍历二叉树,遍历到一个结点时,交换其左右两个子结点。
代码:
递归版本
void Mirro(BTree *T)
{
if (T == NULL || (T->left == NULL && T->right == NULL))
return ;
BTree *tmp = T->left;
T->left = T->right;
T->right = tmp;
if (T->left != NULL)
Mirro(T->left);
if (T->right != NULL)
Mirro(T->right);
}
void Mirro2(BTree *T)
{
if (T == NULL || (T->left == NULL && T->right == NULL))
return ;
stack<BTree *> s;
s.push(T);
while (!s.empty())
{
BTree *tmp = s.top();
s.pop();
BTree *cur = tmp->left;
tmp->left = tmp->right;
tmp->right = cur;
if (tmp->left != NULL)
s.push(tmp->left);
if (tmp->right != NULL)
s.push(tmp->right);
}
}