标签:小代码
/******************** * http://anycodes.cn/zh/ **********************/ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <stdio.h> #include <string.h> #include <queue> #include <math.h> using namespace std; #define OK 1 #define ERROR 0 #define LINK 0 #define THREAD 1 //the type of data typedef char DataType; typedef int Status; //keep the information of node typedef struct BiThrNode { DataType data; struct BiThrNode *lChild,*rChild; int lTag,rTag; }BiThrNode,*BiThrTree; BiThrTree pre = NULL; char ss[]="123#####";int i=0; //CBFEDA// //preorder the tree Status createBiTree(BiThrTree *T) { char ch; //scanf("%c",&ch); ch=ss[i++]; if(ch == ‘\n‘|| ch == ‘\t‘) { return OK; } if(ch == ‘#‘) *T = NULL; else { *T = (BiThrNode *)malloc(sizeof(BiThrNode)); (*T)->data = ch; (*T)->rTag = LINK; (*T)->lTag = LINK; createBiTree(&(*T)->lChild); createBiTree(&(*T)->rChild); } return OK; } void InThreading(BiThrTree t) { if(t) { InThreading(t->lChild); cout<<" [ "<<t->lTag<<" ] "<<t->data<<" [ "<<t->rTag<<" ] "; if(!t->lChild) { t->lTag = THREAD; t->lChild = pre; } if(!t->rChild) { pre->rTag = THREAD; pre->rChild = t; } pre = t; InThreading(t->rChild); } } Status InOrderThreading(BiThrTree *Thrt,BiThrTree T) { *Thrt = (BiThrTree)malloc(sizeof(BiThrNode)); (*Thrt)->lTag = LINK; (*Thrt)->rTag = THREAD; (*Thrt)->rChild = *Thrt; if(!T) { (*Thrt)->lChild = *Thrt; } else { (*Thrt)->lChild = T; pre = *Thrt; InThreading(T); pre->rChild = *Thrt; pre->rTag = THREAD; (*Thrt)->rChild = pre; } return OK; } void lay(BiThrTree root,int n) /*/ 层次打印 /*/ { //assert(root) int kk=n; while(kk--) { int k=1; int m=1;int i=0; BiThrTree b=root; queue<BiThrTree> q; q.push(b); while(!q.empty()) { b=q.front(); if(b->lChild) q.push(b->lChild); if(b->rChild) q.push(b->rChild); m=pow(2,k-1); for(i=0;i<n/2;i++) cout<<" ";cout<<b->data; q.pop(); while(--m) { for(i=0;i<2*(n/2)+1;i++) cout<<" "; if(!q.empty()) { b=q.front(); if(b->lChild) q.push(b->lChild); if(b->rChild) q.push(b->rChild); cout<<b->data; q.pop(); } else cout<<"#"; } cout<<endl; n=n/2; k++; } } } int main() { BiThrTree base = NULL,thrdBase = NULL; createBiTree(&base); InOrderThreading(&thrdBase,base); //lay(thrdBase,2); return 0; } /***** OUT PUT************* [ 0 ] 3 [ 0 ] [ 0 ] 2 [ 0 ] [ 0 ] 1 [ 0 ] ?? **********************/
标签:小代码
原文地址:http://wzsts.blog.51cto.com/10251779/1770248