二叉树
#include<iostream> #include<stack> #include<queue> using namespace std; int maxsize=101; typedef struct BTNode{ int data; int lTag;//lTag=0左孩子;lTag=1前驱节点 int rTag;//rTag=0右孩子;rTag=1后继节点 BTNode * rchild; BTNode * lchild; }BTNode; void visit(BTNode *p){ cout<<p->data<<' '; } //中序线索化 void inThread(BTNode *p,BTNode *&pre){ if(p!=NULL){ inThread(p->lchild,pre); if(p->lchild == NULL){ p->lchild=pre; p->lTag=1; } if(pre !=NULL && pre->rchild == NULL){ pre->rchild=p; pre->rTag=1; } pre = p; inThread(p->rchild,pre); } } //前序线索化 void preThread(BTNode *p,BTNode *&pre){ if(p !=NULL){ if(p->lchild == NULL){ p->lchild=pre; p->lTag=1; } if(pre !=NULL && pre->rchild == NULL){ pre->rchild=p; pre->rTag=1; } pre=p; if(p->lTag == 0){ preThread(p->lchild,pre); } if(p->rTag == 0){ preThread(p->rchild,pre); } } } //后序线索化 void postThread(BTNode *p,BTNode *&pre){ if(p != NULL){ postThread(p->lchild,pre); postThread(p->rchild,pre); if(p->lchild == NULL){ p->lchild =pre; p->lTag=1; } if(pre !=NULL && pre->rchild == NULL){ pre->rchild = p; pre->rTag=1; } pre=p; } } //前序二叉树的前序遍历 void preTorder(BTNode *p){ if(p != NULL){ BTNode *tbt=p; while(tbt != NULL){ while(tbt->lTag == 0){ visit(tbt); tbt=tbt->lchild; } visit(tbt); tbt=tbt->rchild; } } } //递归遍历 void preorder(BTNode *p){ if(p != NULL){ visit(p); preorder(p->lchild); preorder(p->rchild); } } void inorder(BTNode *p){ if(p !=NULL){ inorder(p->lchild); visit(p); inorder(p->rchild); } } void postorder(BTNode *p){ if(p != NULL){ postorder(p->lchild); postorder(p->rchild); visit(p); } } //非递归遍历 void preorderNonrecursion(BTNode *bt){ if(bt != NULL){ BTNode *stack[maxsize]; int top =-1; BTNode *p=NULL; stack[++top]=bt; while(top !=-1){ p=stack[top--]; visit(p); if(p->rchild !=NULL){ stack[++top]=p->rchild; } if(p->lchild !=NULL){ stack[++top]=p->lchild; } } } } void postorderNonrecursion(BTNode *bt){ if(bt !=NULL){ BTNode *stack1[maxsize];int top1=-1; BTNode *stack2[maxsize];int top2=-1; BTNode *p=NULL; stack1[++top1]=bt; while(top1 !=-1){ p=stack1[top1--]; stack2[++top2]=p; if(p->lchild != NULL){ stack1[++top1]=p->lchild; } if(p->rchild !=NULL){ stack1[++top1]=p->rchild; } } while( top2!=-1){ p=stack2[top2--]; visit(p); } } } void inorderNoncursion(BTNode *bt){ if(bt !=NULL){ BTNode *stack[maxsize];int top=-1; BTNode *p=NULL; p=bt; while(top !=-1 || p!=NULL){ while(p !=NULL){ stack[++top]=p; p=p->lchild; } if(top !=-1){ p=stack[top--]; visit(p); p=p->rchild; } } } } //层次遍历 void level(BTNode *bt){ if(bt != NULL){ int front,rear; BTNode *que[maxsize]; front=rear=0; BTNode *p; rear=(rear+1)%maxsize; que[rear]=bt; while(front != rear){ front=(front+1)%maxsize; p=que[front]; visit(p); if(p->lchild != NULL){ rear=(rear+1)%maxsize; que[rear]=p->lchild; } if(p->rchild != NULL){ rear=(rear+1)%maxsize; que[rear]=p->rchild; } } } } int main(){ return 0; }
1.前序线索二叉树
2.中序线索二叉树
3.后序线索二叉树