标签:delete new cin const 两个指针 过程 bool variable 线索二叉树
A.遍历二叉树是以一定的规则将二叉树中的结点排列成一个线性序列(DLR、LDR、LRD、DRL、RLD、RDL),这实质上是对非线性结构进行线性化操作。
B.将二叉树线索化能够不用递归,通过找到后继来线性地遍历二叉树
C.前驱、后继的信息是在动态遍历的过程中才知道的,需要保存下来,而n个结点的二叉链表有n+1个空链域,不妨把这些空链域利用起来储存前驱或后继的信息,而不用在结点中新增两个指针域专门指示前驱、后继,降低了存储密度。
D.中序遍历中,结点的后继:
a.若结点rTag==1,则rChild为后继
b.若结点rTag==0,即结点有右孩子,则后继为右子树中第一个被访问的结点,即右子树最左下的结点
1.中序遍历线索二叉树
void inTraverseThrBiTree(ThrBiTree head){ ThrBiTree p=head->lChild; while(p!=head){ while(p->lTag==0) p=p->lChild; visit(p->data); while(p->rTag==1&&p->rChild!=head){ p=p->rChild; visit(p->data); } p=p->rChild; } }
2.中序线索化二叉树
void inThreading(ThrBiTree p,ThrBiTree &pre){ if(p){ p->lTag=0;p->rTag=0; inThreading(p->lChild,pre); if(!p->lChild){ p->lTag=1; p->lChild=pre; } if(!pre->rChild){ pre->rTag=1; pre->rChild=p; } pre=p; inThreading(p->rChild,pre); } } bool inThreadingBiTree(ThrBiTree &head,ThrBiTree T){ if(!(head=new ThrBiTNode)) return false; head->lTag=0; head->rTag=1; head->rChild=head; if(!T) head->lChild=head; else{ head->lChild=T; ThrBiTree pre=head;//pre can also be a global variable , which dosen‘t have to be passed as an argument. inThreading(T,pre); pre->rTag=1; pre->rChild=head; head->rChild=pre; } pre=NULL; return true; }
3.删除分配给线索二叉树的内存空间
void deleteThrBiTree(ThrBiTree &head){ //error example /*if(T){ ThrBiTree L=T->lChild,R=T->rChild; deleteTree(L); delete T; T=NULL; deleteTree(R); }*/ ThrBiTree p=head->lChild,q=NULL; while(p!=head){ while(p->lTag==0) p=p->lChild; q=p; while(q->rTag==1&&q->rChild!=head){ p=p->rChild; delete q; q=p; } p=p->rChild; } delete head; head=NULL; }
测试//中序遍历线索二叉树+二叉树中序线索化
#include<iostream> using namespace std; typedef struct BiTNode{ int data; BiTNode *lChild,*rChild; int lTag,rTag; }ThrBiTNode,*ThrBiTree; void visit(int a){ cout<<a<<" "; } bool preAndInCreateBiTree(ThrBiTree &p,int *preOrder,int *inOrder,int length){ if(length>0){ if(!(p=new ThrBiTNode)) return false; p->data=preOrder[0]; int i; for(i=0;i<length&&inOrder[i]!=preOrder[0];++i); preAndInCreateBiTree(p->lChild,preOrder+1,inOrder,i); preAndInCreateBiTree(p->rChild,preOrder+i+1,inOrder+i+1,length-i-1); }else{ p=NULL; } return true; } int main(){ int n,*preOrder,*inOrder; cout<<"Input the number of nodes : "; cin>>n; preOrder=new int[n]; inOrder=new int[n]; cout<<"input the pre-order sequence : "<<endl; for(int i=0;i<n;++i) cin>>preOrder[i]; cout<<"input the in-order sequence : "<<endl; for(int i=0;i<n;++i) cin>>inOrder[i]; ThrBiTree T; ThrBiTree head; if(!preAndInCreateBiTree(T,preOrder,inOrder,n)){ cout<<"fail to construct this tree"<<endl; }else{ inThreadingBiTree(head,T);
cout<<"In-traverse:"<<endl; inTraverseThrBiTree(head); } deleteThrBiTree(head); }
标签:delete new cin const 两个指针 过程 bool variable 线索二叉树
原文地址:https://www.cnblogs.com/NoerForest/p/14612334.html