算法题:二叉树的构造

52 篇文章 0 订阅
#include <iostream>
using namespace std;

template<typename Type>
struct Node
{
	Node<Type> *right;
	Node<Type> *left;
	Type data;
	Node(Type d = Type()) :data(d), right(NULL), left(NULL){}
};

template<typename Type>
class MyTree
{
public:
	MyTree() :root(NULL)
	{}
	void Printf()
	{
		Printf(root);
	}

	void Create_tree_VL_(char *VLR,char *LVR)
	{
		int n = strlen(LVR);
		_create_tree_VL_(root,VLR,LVR,n);
	}
	void Create_tree_LL_(char *LVR, char *LRV)
	{
		int n = strlen(LRV);
		_create_tree_LL_(root, LVR, LRV, n);
	}
private:
	void _create_tree_LL_(Node<Type> *&t, char *LVR, char *LRV, int n)
	{
		if (n == 0)return;
		int i = 0;
		while (LRV[n - 1] != LVR[i])i++;
		t = new Node<Type>(LRV[n-1]);

		_create_tree_LL_(t->right,LVR+i+1,LRV+i,n-i-1);
		_create_tree_LL_(t->left, LVR, LRV, i);

	}
	void _create_tree_VL_(Node<Type> *&t, char *VLR, char *LVR, int n)
	{
		if (n == 0)return;
		int i = 0;
		while (VLR[0] != LVR[i])i++;
		t = new Node<Type>(VLR[0]);

		_create_tree_VL_(t->left,VLR+1,LVR,i);
		_create_tree_VL_(t->right, VLR + i + 1, LVR + i + 1, n - i - 1);
	}
	void Printf(Node<Type> *t)
	{
		if (t == NULL)return;
		else
		{
			cout << t->data << "  ";
			Printf(t->left);
			Printf(t->right);
		}
	}
private:
	Node<Type> *root;
};

int main()
{
	char VLR[] = "ABCDEFG";
	char LVR[] = "CBDAFEG";
	char LRV[] = "CDBFGEA";
	//由前续及中序构造二叉树。
	MyTree<char> mt;
	mt.Create_tree_VL_(VLR,LVR);
	mt.Printf();
	cout << endl;
	MyTree<char> my;
	//由中序及后续构造二叉树。
	my.Create_tree_LL_(LVR,LRV);
	my.Printf();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值