线索化 树

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值