您的位置:首页 > 其它

不用堆栈实现树的先序遍历

2015-09-03 18:29 459 查看
通常实现树的先序遍历时,我们都需要一个栈来记录位置信息,如果一颗二叉树当中本来就保存了指向父亲的节点,那么我们可以不用堆栈来实现先序遍历。

#include<iostream>
using namespace std;
class node
{
public:
char value;
node *parent,*left,*right;
node(char v):parent(0),left(0),right(0)
{
value=v;
}
};
void first(node *r)
{
if(r!=NULL)
{
cout<<r->value<<endl;
first(r->left);
first(r->right);
}
}
void fun(node *r)
{
node *p=r;
node *q;
bool xunhuan=true;

while(xunhuan)
{
if(p)
{
cout<<p->value<<endl;
if(p->left!=NULL)// 往左走
{
p=p->left;
}
else
{
if(p->right!=NULL)
{
p=p->right;
}
else
{
bool flag=true;
while(true)
{
while(p->parent!=NULL&&p->parent->right==p)
p=p->parent;
if(p->parent==NULL)
{
xunhuan=false;
break;
}

p=p->parent;
while(p->parent==NULL||p==p->parent->left)
{
if(p->right!=NULL)
{
p=p->right;
flag=false;
break;
}
}
if(!flag)
{
flag=true;
break;
}
if(p->parent==NULL)
{
xunhuan=false;
break;
}

}

}
}
}
}
}
void main()
{
node A('A'),B('B'),C('C'),D('D'),E('E'),F('F');
A.left=&B;
A.right=&C;
B.parent=&A;
C.parent=&A;
B.left=&D;
B.right=&E;
D.parent=&B;
E.parent=&B;
C.left=&F;
F.parent=&C;
first(&A);
cout<<"循环遍历"<<endl;
fun(&A);

system("pause");

}


以上代码可以直接运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: