树——二叉树的镜像

来源:互联网 发布:mysql 查看表空间大小 编辑:程序博客网 时间:2024/06/04 19:17

这里写图片描述

递归实现:

void Mirrordisplay(BitTree &b) {    if (!b)        return;//这里要考虑到最开始b就传入了一颗空树!!!    if ((b->left == nullptr) && (b->right == nullptr))        return;//到了叶子结点返回了    BitTree c = b->left;    b->left = b->right;    b->right = c;    if (b->left)        Mirrordisplay(b->left);    if (b->right)        Mirrordisplay(b->right);}

非递归实现:

void Mirror_nr_display(BitTree &b) {    if (!b)        return;    stack<BitTree> s;    s.push(b);    while (s.size()) {        BitTree pNode = s.top();        s.pop();        if ((pNode->left != nullptr) || (pNode->right != nullptr)) {            BitTree temp = pNode->right;            pNode->right = pNode->left;            pNode->left = temp;        }        if (pNode->left != nullptr)            s.push(pNode->left);        if (pNode->right != nullptr)            s.push(pNode->right);    }}
原创粉丝点击