求二叉树的镜像

输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。

分析:

(1)递归的思想很简单:如果左子树和右子树都已经完成了镜像转换,则直接将它们在根节点下的顺序交换一下,整棵树就完成了镜像转换;

(2)循环:问题实际上要将每个节点的孩子的左右顺序交换一下,所以用广度优先的顺序遍历一遍就行,求解过程中需要队列作为辅助数据结构。

#include <iostream>
#include <queue>
using namespace std;


struct BTreeNode
{
    BTreeNode* pLeft;
    BTreeNode* pRight;
    BTreeNode(int _value) {
        value = _value;
        pLeft = pRight = NULL;
    }
    int value;
};


void printTree(BTreeNode* root) {
    if(root->pLeft != NULL) {
        printTree(root->pLeft);
        cout << " ";
    };
    cout << root->value;
    if(root->pRight != NULL) {
        cout << " ";
        printTree(root->pRight);
    }
}


/**
* Recursive version.
*/
void doMirrorTransRecursive(BTreeNode* root) {
    if(root->pLeft != NULL) doMirrorTransRecursive(root->pLeft);
    if(root->pRight != NULL) doMirrorTransRecursive(root->pRight);
    BTreeNode* temp = root->pLeft;
    root->pLeft = root->pRight;
    root->pRight = temp;
}


/**
* Loop version.
*/
void doMirrorTransLoop(BTreeNode* root) {
    queue<BTreeNode*> q;
    q.push(root);
    while(!q.empty()) {
        BTreeNode* r = q.front();
        q.pop();
        if(r->pLeft != NULL) q.push(r->pLeft);
        if(r->pRight != NULL) q.push(r->pRight);
        BTreeNode* temp = r->pLeft;
        r->pLeft = r->pRight;
        r->pRight = temp;
    }
}


int main() {
    // case 1:
    BTreeNode* root = new BTreeNode(8);
    root->pLeft = new BTreeNode(6);
    root->pLeft->pLeft = new BTreeNode(5);
    root->pLeft->pRight = new BTreeNode(7);


    root->pRight = new BTreeNode(10);
    root->pRight->pLeft = new BTreeNode(9);
    root->pRight->pRight = new BTreeNode(11);


    cout << "Traverse the original tree in mid-order" << endl;
    printTree(root);
    cout << endl;


    cout << "Do mirror transform in recursive style to the original \
     tree and traverse the transformed tree (t1) in mid-order" << endl;
    doMirrorTransRecursive(root);
    printTree(root);
    cout << endl;


    cout << "Do mirror transform in circularly style to the \
     t1 and traverse the transformed in mid-order" << endl;
    doMirrorTransLoop(root);
    printTree(root);
    cout << endl;
    return 0;
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值