数据结构与算法面试题80道(15)

15:

题目:输入一颗二元查找树,将该树转换为它的镜像,

即在转换后的二元查找树中,左子树的结点都大于右子树的结点。

用递归和循环两种方法完成树的镜像转换。 

例如输入:

    8

   / \

 6   10

 /\    /\

5 7 9 11

 

输出:

      8

     / \

  10   6

  /\    /\

11 9 7 5

 

定义二元查找树的结点为:

struct BSTreeNode // a node in the binary search tree (BST)

{

 int m_nValue; // value of node

 BSTreeNode *m_pLeft; // left child of node

 BSTreeNode *m_pRight; // right child of node

};

 

 挺简单的,直接上代码。都是套路

#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
struct BSTreeNode{
    int m_nValue;
    BSTreeNode *m_pLeft;
    BSTreeNode *m_pRight;
};

void addNode(BSTreeNode *&root,int value){
    if(root==NULL){
        BSTreeNode *tree=new BSTreeNode();
        if(tree==NULL) {cout<<"内存错误"<<endl;return ;}
        tree->m_nValue=value;
        tree->m_pLeft=NULL;
        tree->m_pRight=NULL;
        root=tree;
    }else if(root->m_nValue>value) addNode(root->m_pLeft,value);
    else if(root->m_nValue<value) addNode(root->m_pRight,value);
    else cout<<"结点重复"<<endl;
}

//交换结点的左右指针
void swap(BSTreeNode *root){
    BSTreeNode *tree=new BSTreeNode();
    tree=root->m_pLeft;
    root->m_pLeft=root->m_pRight;
    root->m_pRight=tree;
}

//递归方法求镜像
void mirrorTree(BSTreeNode *root){
    if(root==NULL) return ;
    mirrorTree(root->m_pLeft);
    mirrorTree(root->m_pRight);
    swap(root);
}

//可以用队列,也可以用栈,这里是用的队列,其实都是一样的,只是转换的顺序不同
void loopMirrorTree(BSTreeNode *root){
    queue<BSTreeNode*>q;
    q.push(root);

    while(!q.empty()){
        BSTreeNode *t=q.front();
        q.pop();
        swap(t);
        if(t->m_pLeft!=NULL) q.push(t->m_pLeft);
        if(t->m_pRight!=NULL) q.push(t->m_pRight);
    }
}

//中序遍历看结果
void inOrderTree(BSTreeNode *root){
    if(root==NULL) return;
    if(root->m_pLeft!=NULL) inOrderTree(root->m_pLeft);
    cout<<root->m_nValue<<" ";
    if(root->m_pLeft!=NULL) inOrderTree(root->m_pRight);
}

int main(){
    //建树
    BSTreeNode *root=NULL;
    addNode(root,8);
    addNode(root,6);
    addNode(root,10);
    addNode(root,5);
    addNode(root,7);
    addNode(root,9);
    addNode(root,11);

    //先中序遍历看结果
    inOrderTree(root);
    cout<<endl;
    //用递归翻转,再将结果打印出来严重
    mirrorTree(root);
    inOrderTree(root);
    cout<<endl;
    //最后用循环再次翻转,对比第一次结果,比较是否相同
    loopMirrorTree(root);
    inOrderTree(root);
    cout<<endl;
    return 0;
}

 

posted @ 2016-03-11 14:08  dreamOwn  阅读(417)  评论(0编辑  收藏  举报