#include "stdio.h"
#include "stdlib.h"
typedef struct _Node{
int val;
struct _Node* lf;
struct _Node* rt;
}Node, *pNode;
int num[] = {3, 8, 1, 4, 0, 2, 9, 7, 6, 5};
int n = 10;
void insert(pNode* r, int v){
pNode w = *r;
if(!w){
w = (pNode)malloc(sizeof(Node));
w->val = v;
w->lf = w->rt = 0;
*r = w;
return;
}
if(v<=w->val)
insert(&(w->lf), v);
else
insert(&(w->rt), v);
}
pNode* line(pNode r, pNode* l){
pNode* pre;
if(!r) return l;
pre = line(r->lf, l);
if(*pre==0){
*pre = r;
r->lf = 0;
}
else{
(*pre)->rt = r;
r->lf = *pre;
}
return line(r->rt, &r);
}
int main(){
int i;
pNode r = 0;
pNode h = 0;
pNode t, p;
for(i=0; i<n; i++)
insert(&r, num[i]);
t = *line(r, &h);
printf("From start to end: ");
p = h;
while(p){
printf("%d ", p->val);
p = p->rt;
}
printf("\n");
printf("From end to start: ");
p = t;
while(p){
printf("%d ", p->val);
p = p->lf;
}
printf("\n");
return 0;
}
结果:
From start to end: 0 1 2 3 4 5 6 7 8 9
From end to start: 9 8 7 6 5 4 3 2 1 0