+ -
当前位置:首页 → 问答吧 → 中序遍历有问题

中序遍历有问题

时间:2011-12-19

来源:互联网

复制内容到剪贴板
代码:
#include<iostream>
using namespace std;
template<class T>
class BiTree;
template<class T>
class BTnode
{
friend class BiTree<T>;
private:
T data;
BTnode<T> *LC,*RC;//左指针,右指针
public:
BTnode(){LC=RC=0;}

};
template<class T>
class BiTree
{
private:
BTnode<T> *root;
void create(BTnode<T> * &t);
void inorder(BTnode<T>* &t);
public:
BiTree(){root=NULL;}
void createBT(){create(root);}//创建二叉树
void inorderBT(){inorder(root);}//非递归中序遍历

};
template<class T>
void BiTree<T>:: create(BTnode <T>* &t)
{
char ch;
cin>>ch;
if(ch=='#')
t=NULL;//#符表示空树
else
{
t=new BTnode<T>;
t->data=ch;
create(t->LC);
create(t->RC);
}
}
template<class T>
void BiTree<T>::inorder(BTnode<T>*&t)
{
int stack[100];
int top=-1;
while(t!=NULL||top!=-1)
{
while(t!=NULL)
{
top++;
stack[top]=t->data;
t=t->LC;
}
if(top!=-1)
{
t->data=stack[top];
top--;
cout<<t->data<<" ";
t=t->RC;
}
}

}
int main()
{
BiTree<char> c1;
cout<<"请用先序法输入:"<<endl;
c1.createBT();
cout<<"中序遍历输出:"<<endl;
c1.inorderBT();
return 0;
}

作者: 逍遥小仙   发布时间: 2011-12-19

小仙你好,这段时间我一直在忙课程设计,没有时间帮你们调试代码,这里是我以前写的一个遍历代码,希望能有点帮助,见谅。
  D4 N0 |: l  K1 \" c7 bhttp://bbs.51cto.com/thread-902992-1.html
' I: L! k, N3 L& d
引用:
原帖由 逍遥小仙 于 2011-12-19 12:18 发表
; G4 @+ H: F6 t& M5 h, ^2 W#include
' {% l) ?6 F% Ousing namespace std;' I# T! e2 L8 K  j# |0 S
template7 u+ A( |0 C6 W- `
class BiTree;
) M! F0 V$ ]9 c; G3 k; i) h; Ntemplate# G: e/ \' o0 T  M( I, t
class BTnode
4 D; _- V, e9 y! t, S2 h) n{ 0 q9 d% |0 ^" r& S
friend class BiTree;
  D: V, {- n" E5 Dprivate:1 j! p; u) b+ w. P; k
T data;6 _  E' Z% J* m: ]
BTnode *LC,*RC;//左指针,右指针
& K2 l" m! x, m3 [" H8 T; dpublic:
) {1 s! p, w, iBTnode(){LC=RC=0;}0 g% L9 N+ r6 i/ W; R0 @
' v! {$ |4 V" ^- W- E: M' j4 J7 q
};' y- V( b, r1 y, d3 Q) J2 s. [
template) ], E6 O" z! z0 t8 w' F
class BiTree5 L) o$ F3 O! K9 c9 e/ j5 d
{ ...

作者: Bill_Hoo   发布时间: 2011-12-19