根据二叉树的前序,中序以及中序,后序序列构造二叉树并输出

相信题目已经说得够清楚了,递归方法,主要通过数组指针的移动和下标的转换来操作。水平有限,不吝赐教~

#include <iostream>
#include <queue>
#include <stack>
using namespace std;
class Node{
	public:
		int element;         //数据
		Node * leftChild;        //左孩子结点
		Node * rightChild;       //右孩子结点
	public:
		Node(){
			element = 0;
			leftChild = rightChild = NULL;
		}
		Node(int el,Node* l,Node* r ){
			element = el;
			leftChild = l;
			rightChild = r;
		}

		~Node(){}   //默认析构
//		void setLeftChild(Node<T>* l);   //设置左孩子结点
//		void setRightChild(Node<T>* r);   //设置右孩子结点
//		void setValue(const T& val);   // 设置该结点数据
//		T getvalue() const;        //返回该结点的数据

//		bool isLeaf() const;  //判断该节点是否是叶子结点
		
};



Node* restore(int* ppos,int* ipos,int n)   //前序加中序
{
	Node* ptr;
	int* rpos;
	int k;
	if (n<=0)
		return NULL;
	ptr = new Node;
	ptr->element = *ppos;
	for (rpos = ipos;rpos < ipos + n;rpos++)
		if (*rpos == *ppos)
			break;
	
	k = rpos - ipos;
	ptr->leftChild = restore(ppos+1,ipos,k);
	ptr->rightChild = restore(ppos+1+k,rpos+1,n-1-k);
	return ptr;


}

Node* postore(int* ipos,int* postpos,int n)   //中序加后序
{
	Node* ptr;
	int* rpos;
	int k;
	if (n<=0)
		return NULL;
	ptr = new Node;
	ptr->element = postpos[n-1];
	for (rpos = ipos;rpos <= ipos + n;rpos++)
		if (*rpos == ptr->element)
			break;

	k = &ipos[n-1] - rpos;
	if (k>=0)
	{
		ptr ->leftChild = postore(ipos,postpos,n-k-1);
		ptr ->rightChild = postore(rpos+1,postpos+n-k-1,k);///////////////////////搞定了!!
	}
	return ptr;
}
void postOrder(Node* root)   //后序遍历
{
	if (root != NULL)
	{
		postOrder(root->leftChild);
		postOrder(root->rightChild);
		cout<<root->element<<"  ";
	}
}

void preOrder(Node* root)   //前序遍历
{
	if (root != NULL)
	{
		cout<<root->element<<"  ";
		preOrder(root->leftChild);
		preOrder(root->rightChild);
	}
}

int main()
{
	Node* root1 = NULL;
	Node* root2 = NULL;
	int ppos[] = {1,2,3,4,5};
	int ipos[] = {3,4,2,5,1};
	int postpos[] = {4,3,5,2,1};
	root1 = restore(ppos,ipos,5);
	root2 = postore(ipos,postpos,5)	;
/*	cout<<"the preorder  is: ";
	print_str(pre_order);
	cout<<endl;

	cout<<"the inorder   is: ";
	print_str(in_order);
	cout<<endl;
	cout<<"the postorder is: ";
	postorder(root);
	cout<<endl;
	*/

	cout<<"=======前序遍历======="<<endl;
	preOrder(root2);
	cout<<endl<<"=======后序遍历======="<<endl;
	postOrder(root1);

	return 0;

}

  

posted @ 2013-11-14 20:24  too_young  阅读(293)  评论(0)    收藏  举报