算法题:二叉树的构造

#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;
}

    原文作者:让我们荡起双脚
    原文地址: https://blog.csdn.net/liuhuiyan_2014/article/details/47338819
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞