问题:把一个二叉查询树保存到一个文件,然后通过这个文件把这个二叉查询树还原出来。
我们使用pre-order遍历把一个二叉查询树保存,原因是只有pre-order遍历是从root开始保存,这样,当我们读取的时候,才能够把那个值放在root。
这里我用print来表示保存。
我们把保存的二叉树复原的时候,只需要使用二叉树的插入方法即可。 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
本文介绍了一种使用前序遍历来保存二叉查询树的方法,并详细阐述了如何通过二叉树的插入操作将保存的二叉树还原。此外,还提供了一个复杂度为O(N)的算法用于读取保存的二叉查询树,以及针对非二叉查询树的保存和还原策略。
9075

被折叠的 条评论
为什么被折叠?



