二叉树之先序建立二叉树

以下代码是我参考网上先序建立二叉树的定义,建立的二叉树,并再先序遍历每个节点

//-------------------------------------------------------------
//********先序建立二叉树,并再先序遍历二叉树*******************
//-------------------------------------------------------------

#include <iostream>
using namespace std;

class Tree
{
public:
	Tree();
	~Tree();
	int data;
	Tree* lchild;
	Tree* rchild;
	Tree* Create();
	void  PreOrder(Tree* t);

};
Tree::Tree()
{
	data=0;

	lchild=NULL;
	rchild=NULL;
}
Tree* Tree::Create()
{
	int x;
	Tree* root;
	//Tree* saveRoot;
    cin>>x;
	if(x==0)
	{
		root=0;
	}
	   
	else
	{
		root=new Tree;
		root->data=x;
		root->lchild=Create();
		root->rchild=Create();
		//cout<<"左树"<<endl;

	}
	return root;
}
void Tree::PreOrder(Tree* T)
{
	if(T!=NULL)
	{
		cout<<T->data;
		PreOrder(T->lchild);
		PreOrder(T->rchild);
	}

}


//------------------------------------------------
// **********测试程序***********
//------------------------------------------------
#include "Node.h"
using namespace std;

void main()
{
	Tree* Tnode;
	Tree* Tree;
	Tnode=Tree->Create();
	
	Tree->PreOrder(Tnode);

}


 

猜你喜欢

转载自blog.csdn.net/songzhaorong/article/details/22995849
今日推荐