bool Binary_Tree::Save(string filename)
{
ofstream fout(filename.c_str());
if (fout.fail()) return false;
fout<<size<<endl;
if (root) Save(root,1,fout);
fout.close();
return true;
}
void Binary_Tree::Save(Node *p,int id,ofstream &fout)
{
fout<<id<<' '<<p->data<<endl;
if (p->left) Save(p->left,id*2,fout);
if (p->right) Save(p->right,id*2+1,fout);
}
void Binary_Tree::Clear()
{
if (root!=0) Clear(root);
root=0;
size=0;
}
bool Binary_Tree::Load(string filename)
{
ifstream fin(filename.c_str());
int n;
Node *p;
int i,j;
int count;
Clear();
if (fin.fail()) return false;
if (!(fin>>n)) return false;
count=0;
size=n;
for (i=0;i<n;i++)
{
int id,data;
if (!(fin>>id>>data) || id<=0)
{
Clear();
fin.close();
return false;
}
if (root==0)
{
root=new Node;
count++;
}
p=root;
for (j=30;j>=0;j--)
if (id & (1<<j)) break;
while (j--)
{
if (!(id & (1<<j)))
{
if (p->left==0)
{
p->left=new Node;
p->left->parent=p;
count++;
}
p=p->left;
}
else
{
if (p->right==0)
{
p->right=new Node;
p->right->parent=p;
count++;
}
p=p->right;
}
}
p->data=data;
p=0;
}
fin.close();
if (count>n)
{
Clear();
return false;
}
return true;
}
面试题93:二叉树的存储和还原
最新推荐文章于 2024-10-14 10:45:00 发布