二叉查询树的保存和读取(Serialization/Deserialization)

问题:把一个二叉查询树保存到一个文件,然后通过这个文件把这个二叉查询树还原出来。


我们使用pre-order遍历把一个二叉查询树保存,原因是只有pre-order遍历是从root开始保存,这样,当我们读取的时候,才能够把那个值放在root。


这里我用print来表示保存。


public void preOrderWrite(Node root) { if (root!= null) { System.out.println(root.value); preOrderWrite(root.leftChild); preOrderWrite(root.rightChild); } }
我们把保存的二叉树复原的时候,只需要使用二叉树的插入方法即可。

public static Node insert(Node root, int data) { // 1. If the tree is empty, the new node is the root if (root == null) { return new Node(data); } else { // 2. Otherwise, recur down the tree if (data <= root.data) root.leftChild = insert(root.leftChild, data); else root.rightChild = insert(root.rightChild, data); } return root; }
插入操作的复杂度是:O(nlgn).


这里有个复杂度为O(N)的算法,贴出来。

void readBSTHelper(int min, int max, int &insertVal, BinaryTree *&p, ifstream &fin) { if (insertVal > min && insertVal < max) { int val = insertVal; p = new BinaryTree(val); if (fin >> insertVal) { readBSTHelper(min, val, insertVal, p->left, fin); readBSTHelper(val, max, insertVal, p->right, fin); } } } void readBST(BinaryTree *&root, ifstream &fin) { int val; fin >> val; readBSTHelper(INT_MIN, INT_MAX, val, root, fin); }


如果不是二叉查询树,而是二叉树,上面这个方法是不能用的。我们可以利用分层打印的思想,对二叉树进行保存和读取。


参考: http://www.ihas1337code.com/2010/09/saving-binary-search-tree-to-file.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值