原程序如下,添加了雙親域parent和標志域mark;不知道哪裡不對:
#include"iostream"
using namespace std;
class BinTree;
class BinNode
{
private:
int data;
BinNode *lchild;
BinNode *rchild;
BinNode *parent;
int mark;
friend class BinTree;
};
class BinTree
{
private:
BinNode *root;
public:
BinTree()
{
root=0;
}
BinNode *Get_Root()
{
return root;
}
BinNode *Create_Tree(BinNode *r) //先序建立二叉樹
{
int d;
cout<<"輸入數據(0代表空):";
cin>>d;
if(d==0)
return NULL;
else
{
r=new BinNode;
r->data=d;
r->lchild=Create_Tree(r->lchild);
r->rchild=Create_Tree(r->rchild);
}
root=r;
return r;
}
void InOrder_rec1(BinNode *p) //xian序遍歷
{
if(p)
{
cout<<p->data<<" ";
InOrder_rec1(p->lchild);
InOrder_rec1(p->rchild);
}
}
void InOrder_rec2(BinNode *p) //中序遍歷
{
if(p)
{
InOrder_rec2(p->lchild);
cout<<p->data<<" ";
InOrder_rec2(p->rchild);
}
}
void PostOrder_rec(BinNode *p)//後續遍歷
{
BinNode*t=p;
t->mark=0;
while (t)
{
switch(t->mark){
case 0:
t->mark=1;
if(t->lchild) t=t->lchild;
break;
case 1:
t->mark=2;
if(t->rchild) t=t->rchild;
case 2:
cout<<t->data<<endl;
t->mark=0;
t=t->parent;
break;
default:;
}
}
}
};
int main()
{
BinTree tree;
BinNode *p=NULL;
p=tree.Create_Tree(p);
cout<<"先序遍歷二叉樹:";
tree.InOrder_rec1(p);
cout<<endl;
cout<<"中序遍歷二叉樹:";
tree.InOrder_rec2(p);
cout<<endl;
cout<<"中序遍歷二叉樹:";
tree.PostOrder_rec(p);
cout<<endl;
}
#include"iostream"
using namespace std;
class BinTree;
class BinNode
{
private:
int data;
BinNode *lchild;
BinNode *rchild;
BinNode *parent;
int mark;
friend class BinTree;
};
class BinTree
{
private:
BinNode *root;
public:
BinTree()
{
root=0;
}
BinNode *Get_Root()
{
return root;
}
BinNode *Create_Tree(BinNode *r) //先序建立二叉樹
{
int d;
cin>>d;
if(d==0)
return NULL;
else
{
r=new BinNode;
r->data=d;
r->lchild=Create_Tree(r->lchild);
r->rchild=Create_Tree(r->rchild);
}
root=r;
return r;
}
void InOrder_rec1(BinNode *p) //xian序遍歷
{
if(p)
{
cout<<p->data<<" ";
InOrder_rec1(p->lchild);
InOrder_rec1(p->rchild);
}
}
void InOrder_rec2(BinNode *p) //中序遍歷
{
if(p)
{
InOrder_rec2(p->lchild);
cout<<p->data<<" ";
InOrder_rec2(p->rchild);
}
}
void PostOrder_rec(BinNode *p)//後序遍歷
{
if(p)
{
InOrder_rec2(p->lchild);
InOrder_rec2(p->rchild);
cout<<p->data<<" ";
}
}
};
int main()
{
BinTree tree;
BinNode *p=NULL;
cout<<"輸入數據(0代表空):";
p=tree.Create_Tree(p);
cout<<"先序遍歷二叉樹:";
tree.InOrder_rec1(p);
cout<<endl;
cout<<"中序遍歷二叉樹:";
tree.InOrder_rec2(p);
cout<<endl;
cout<<"後序遍歷二叉樹:";
tree.PostOrder_rec(p);
cout<<endl;
}