您的位置:首页 > 其它

非递归中序输出二叉搜索树

2010-10-10 12:16 211 查看
代码

#include <iostream>
using namespace std;

struct SBtee
{
SBtee * _p;
SBtee *_l;
SBtee *_r;
int _data;
};

void Print(SBtee * p)
{
cout<<p->_data<<" ";
}
void inorder_tree_walk(SBtee * root)
{
SBtee * last = (SBtee*)1;
SBtee * p = root;

while(p)
{
if(p->_r == last)
{
while (p!=NULL&&p->_r == last)
//找到该结点的第一个父结点,其中该结点在此父结点的左子树上
{
last = p;
p=p->_p;
}
}
else if (p->_l==NULL ||
p->_l==last)
{
Print(p);
last = p;
if (p->_r==NULL)
{
p=p->_p;
}
else
{
p=p->_r;
}
}
else
{
p = p->_l;
}
}
}

int main(int argc, char* argv[])
{
SBtee * pRoot = new SBtee;
pRoot->_data = 150;
pRoot->_p =NULL;

SBtee * p;
pRoot->_l = new SBtee;
pRoot->_l->_data =60;
p = pRoot->_r = new SBtee;
pRoot->_r->_data =180;

pRoot->_r->_p = pRoot->_l->_p = pRoot;

p->_l = new SBtee;
p->_l->_data =170;
p->_l->_l = p->_l->_r = NULL;

p->_r = new SBtee;
p->_r->_data =200;
p->_r->_l = p->_r->_r = NULL;

p->_l->_p =p->_r->_p=p;

p = pRoot->_l;
p->_l = new SBtee;
p->_l->_data = 30;

p->_r=new SBtee;
p->_r->_data =70;

p->_l->_p =p->_r->_p=p;

SBtee * p3 =p->_l;
SBtee * p7 =p->_r;

p3->_l = new SBtee;
p3->_l->_data=20;
p3->_l->_l=p3->_l->_r =NULL;
p3->_r = new SBtee;
p3->_r->_data=40;
p3->_r->_l=p3->_r->_r =NULL;

p3->_l->_p = p3->_r->_p = p3;

p7->_l=NULL;
SBtee * p13 = p7->_r = new SBtee;
p7->_r->_data =130;

p7->_r->_p=p7;

p13->_l = new SBtee;
p13->_l->_data =90;
p13->_l->_l= p13->_l->_r = NULL;

p13->_r = new SBtee;
p13->_r->_data =131;
p13->_r->_l =NULL;

p13->_l->_p = p13->_r->_p = p13;

p = p13->_r->_r= new SBtee;
p->_data =132;
p->_l = p->_r = NULL;

p->_p = p13->_r;

pRoot->_r= NULL;
inorder_tree_walk(pRoot);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: