二叉查询树的保存和读取

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

我们使用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).

如果不是二叉查询树,而是二叉树,上面这个方法是不能用的。这里有两种方法,一种是先把二叉树保存为一颗满二叉树,然后保存在数组里。第二种方法是保存这颗二叉树的先序和中序数组,利用这两个数组来恢复二叉树。

下面部分来自博客:http://blog.csdn.net/niushuai666/article/details/6413024

思路:

先序序列的第一个结点为要构造二叉树的根结点,在中序序列中查找二叉树的根结点,则中序列根结点左边为根结点的左子树的中序序列,右边为根结点的右子树的中序序列。而先序序列根结点后面分别为它的左子树和右子树的先序序列。有了根结点在中序序列的位置,就知道了左子树和右子树的先序序列各自的位置。这样,就知道了根结点两个子树的序列。然后在构造了根结点后,就可以递归调用函数来勾结根结点的左子树和右子树。

string.find()   返回查找元素的下标

string.substr(a, b)   从第a个下标的元素开始截取b个元素 

 代码如下:

struct Node
{
	char data;
	Node * lchild;
	Node * rchild;
};

Node* CreatTree(string pre, string in)
{
	Node * root = NULL;  //树的初始化
	if(pre.length() > 0)
	{
		root = new Node;  //为根结点申请结构体所需要的内存
		root->data = pre[0]; //先序序列的第一个元素为根结点
		int index = in.find(root->data);  //查找中序序列中的根结点位置
		root->lchild = CreatTree(pre.substr(1, index), in.substr(0, index));  //递归创建左子树
		root->rchild = CreatTree(pre.substr(index + 1), in.substr(index + 1)); //递归创建右子树
	}
	return root;
}

http://blog.csdn.net/beiyeqingteng

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值