#include <iostream> #include <deque> using namespace std; const int MaxSize=100; struct BitTree { char data; BitTree *lchild; BitTree *rchild; }; void CreatBitTree(BitTree *&T) { char temp; cin>>temp; if (temp=='#') { T=NULL; } else { T=new BitTree; T->data=temp; CreatBitTree(T->lchild); CreatBitTree(T->rchild); } } void PreOrderTraverse(BitTree *T) //前序遍历 { if (T!=NULL) { cout<<T->data<<" "; PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); } } void InOrderTraverse(BitTree *T) //中序遍历 { if(T!=NULL) { InOrderTraverse(T->lchild); printf("%c ",T->data); InOrderTraverse(T->rchild); } } void PostOrderTraverse(BitTree *T) //后序遍历 { if(T!=NULL) { PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild); cout<<T->data<<" "; } } int TreeDepth(BitTree *T) { if (T==NULL) { return 0; } int nleft=TreeDepth(T->lchild); int nright=TreeDepth(T->rchild); return (nleft>=nright?nleft+1:nright+1); } void LevelOrder(BitTree *T) //层次遍历,使用循环队列 { BitTree *p; BitTree *qu[MaxSize]; int front,rear; front=rear=-1; rear++; qu[rear]=T; while(front!=rear) { front=(front+1)%MaxSize; p=qu[front]; printf("%c ",p->data); if(p->lchild!=NULL) { rear=(rear+1)%MaxSize; qu[rear]=p->lchild; } if(p->rchild!=NULL) { rear=(rear+1)%MaxSize; qu[rear]=p->rchild; } } } void LevelOrder_Solution(BitTree *T) //层次遍历,用了顺序容器中的双端队列 { deque<BitTree *> stacktree; stacktree.push_back(T); while (stacktree.size()!=0) { BitTree *pNode=stacktree.front(); cout<<pNode->data<<" "; stacktree.pop_front(); if (pNode->lchild!=NULL) { stacktree.push_back(pNode->lchild); } if (pNode->rchild!=NULL) { stacktree.push_back(pNode->rchild); } } } void MirrorBitTree(BitTree *T) //求二叉树的镜像,递归实现 { if (T==NULL) { return; } BitTree *pNode=T->lchild; T->lchild=T->rchild; T->rchild=pNode; if (T->lchild!=NULL) { MirrorBitTree(T->lchild); } if (T->rchild!=NULL) { MirrorBitTree(T->rchild); } } int main() { BitTree *Tree; cout<<"Input data of Tree:"; CreatBitTree(Tree); cout<<"前序遍历:"; PreOrderTraverse(Tree); cout<<endl; cout<<"中序遍历:"; InOrderTraverse(Tree); cout<<endl; cout<<"后序遍历:"; PostOrderTraverse(Tree); cout<<endl; int depth=TreeDepth(Tree); cout<<"The Depth of Tree is:"<<depth<<endl; cout<<"层次遍历:"; LevelOrder(Tree); cout<<endl; MirrorBitTree(Tree); cout<<"层次遍历:"; LevelOrder_Solution(Tree); cout<<endl; return 0;