这道题是微软的面试题,大意是给出一个二叉排序树,让你输出排序的链表
二叉排序树参照博客http://blog.csdn.net/hackbuteer1/article/details/7275396
转换部分参照博客http://zhedahht.blog.163.com/
#include <iostream>
#include<cmath>
#include<algorithm>
#include<stdio.h>
#include<cstring>
#include<stack>
using namespace std;
struct node
{
int num;
struct node *lc;
struct node *rc;
};
bool searchtree(node *root ,int data,node *f,node *&p)
{
if(root==NULL)
{
p=f;
return false;
}
else if(root->num==data)
{
p=root;
return true;
}
else if(root->num>data)
{
return searchtree(root->lc,data,root,p);
}
else if(root->num<data)
{
return searchtree(root->rc,data,root,p);
}
}
void buildtree(node *&root,int data)
{
node *p;
node *q;
if(!searchtree(root,data,NULL,p))
{
q=(struct node *)malloc(sizeof(node));
q->num=data;
q->lc=NULL;
q->rc=NULL;
if(p==NULL)
{
root=q;
}
else if(data<p->num)p->lc=q;
else p->rc=q;
}
else return;
}
void convertnode(node *p,node *&lastoflist)
{
if(p==NULL)return;
node *pcurrent=p;
if(pcurrent->lc)
{
convertnode(pcurrent->lc,lastoflist);
}
pcurrent->lc=lastoflist;
if(lastoflist)
lastoflist->rc=pcurrent;
lastoflist=pcurrent;
if(pcurrent->rc)
{
convertnode(p->rc,lastoflist);
}
}
node *zhuanhuan(node *p)
{
node*lastoflist=NULL;
convertnode(p,lastoflist);
node*headoflist=lastoflist;
while(headoflist&&headoflist->lc)
{
headoflist=headoflist->lc;
}
return headoflist;
}
void zhongxubianli(node *p)
{
if(p==NULL)return;
zhongxubianli(p->lc);
printf("%d ",p->num);
zhongxubianli(p->rc);
}
int main()
{
node *ptree=NULL;
int n;
int i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
int x;
scanf("%d",&x);
buildtree(ptree,x);
}
node*phead=zhuanhuan(ptree);
while(phead)
{
printf("%d ",phead->num);
phead=phead->rc;
}
return 0;
}