求二元查找树的镜像

来源:互联网 发布:电脑视频文件修复软件 编辑:程序博客网 时间:2024/05/20 09:48
题目:输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。 
例如输入:
     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<iostream>using namespace std;struct BSTreeNode // a node in the binary search tree (BST){int          m_nValue; // value of nodeBSTreeNode  *m_pLeft;  // left child of nodeBSTreeNode  *m_pRight; // right child of node};void create(BSTreeNode *&p,int *a,int i){if(i>7)return;p=new BSTreeNode;p->m_nValue=a[i];p->m_pLeft=p->m_pRight=NULL;create(p->m_pLeft,a,i*2);create(p->m_pRight,a,i*2+1);}void Turn(BSTreeNode *&p){if(p==NULL)return;BSTreeNode *temp;temp=p->m_pLeft;p->m_pLeft=p->m_pRight;p->m_pRight=temp;Turn(p->m_pLeft);Turn(p->m_pRight);}int main(){BSTreeNode *p;int a[]={0,8,6,10,5,7,9,11};create(p,a,1);Turn(p);return 0;}

0 0