#include<stdio.h> #include<malloc.h> #include<iostream> #include<stack> #include<queue> using namespace std; typedef struct BiTNode { char data,tag; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; int createBiTree(BiTree &T)//create tree by pre order { char data; scanf("%c",&data); if(data=='#') { T=NULL; } else { T=(BiTree)malloc(sizeof(BiTNode)); T->data=data; createBiTree(T->lchild); createBiTree(T->rchild); } return 0; } void visit(BiTree T) { if(T->data!='#') { printf("%c ",T->data); } } void preOrder(BiTree T) { if(T!=NULL) { visit(T); preOrder(T->lchild); preOrder(T->rchild); } } void interOrder(BiTree T) { if(T!=NULL) { interOrder(T->lchild); visit(T); interOrder(T->rchild); } } void postOrder(BiTree T) { if(T!=NULL) { postOrder(T->lchild); postOrder(T->rchild); visit(T); } } void preNROrder(BiTree T) { stack<BiTree> stack; BiTree p=T; while(p!=NULL||!stack.empty()) { if(p!=NULL) { stack.push(p); printf("%c ",p->data); p=p->lchild; } else { p=stack.top(); stack.pop(); p=p->rchild; } } } void interNROrder(BiTree T) { stack<BiTree> stack; BiTree p=T; while(p!=NULL||!stack.empty()) { if(p!=NULL) { stack.push(p); p=p->lchild; } else { p=stack.top(); printf("%c ",p->data); stack.pop(); p=p->rchild; } } } void postNROrder(BiTree T) { stack<BiTree> stack; BiTree p=T; while(p!=NULL||!stack.empty()) { while(p!=NULL) { p->tag='L'; stack.push(p); p=p->lchild; } while(!stack.empty()&&(stack.top())->tag=='R') { p=stack.top(); stack.pop(); printf("%c ",p->data); } if(stack.size()==0) { break; } if(!stack.empty()) { p=stack.top(); p->tag='R'; p=p->rchild; } } } void levelTraverse(BiTree T) { BiTree p=T; queue<BiTree> queue; queue.push(p); while(!queue.empty()) { p=queue.front(); printf("%c ",p->data); queue.pop(); if(p->lchild!=NULL) { queue.push(p->lchild); } if(p->rchild!=NULL) { queue.push(p->rchild); } } } int main() { BiTree T; createBiTree(T); printf("pre order traverse:\n"); preOrder(T); printf("\n"); printf("pre NR order traverse:\n"); preNROrder(T); printf("\n\n"); printf("inter order traverse:\n"); interOrder(T); printf("\n"); printf("inter NR order traverse:\n"); interNROrder(T); printf("\n\n"); printf("post order traverse:\n"); postOrder(T); printf("\n"); printf("post NR order traverse:\n"); postNROrder(T); printf("\n\n"); printf("level traverse:\n"); levelTraverse(T); printf("\n"); return 0; }
原文地址:http://blog.csdn.net/yangxiangyuibm/article/details/39551073