面试题93:二叉树的存储和还原

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; 
} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值