问题:
把一个二叉查询树保存到一个文件,然后通过这个文件把这个二叉查询树还原出来。
我们使用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).
如果不是二叉查询树,而是二叉树,上面这个方法是不能用的。但是,我们可以保存二叉树的先序和中序数组,然后利用这两个数组来恢复二叉树。
思路:
先序序列的第一个结点为要构造二叉树的根结点,在中序序列中查找二叉树的根结点,则中序列根结点左边为根结点的左子树的中序序列,右边为根结点的右子树的中序序列。而先序序列根结点后面分别为它的左子树和右子树的先序序列。有了根结点在中序序列的位置,就知道了左子树和右子树的先序序列各自的位置。这样,就知道了根结点两个子树的序列。然后在构造了根结点后,就可以递归调用函数来勾结根结点的左子树和右子树。
代码:
Node createTree(String preString, String inString) {
Node root = null;
if (preString.length() > 0) {
root = new Node();
root.value = preString.charAt(0);
int index = inString.indexOf(root.value);
root.left = createTree(preString.substring(1, index + 1), inString.substring(0, index));
root.right = createTree(preString.substring(index + 1), inString.substring(index + 1));
}
return root;
}
class Node {
char value;
Node left;
Node right;
}
转载请注明出处:
http://blog.csdn.net/beiyeqingteng