您的位置:首页 > 其它

二叉树之先序建立二叉树

2014-04-05 21:12 99 查看
以下代码是我参考网上先序建立二叉树的定义,建立的二叉树,并再先序遍历每个节点

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

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

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: