刚学数据机构没多久,学校又是讲c的,自己就用c++写的
只哟建立与遍历,其他功能还没完善,坐等完善
//*********************二叉树************************
#include <iostream>
using namespace std;
//**********声明Node为BinaryTree的友元类
class BinaryTree;
//****************二叉树节点类*****************
class Node
{
private:
int Data;
Node* Lchild;
Node* Rchild;
public:
Node();
Node(int Data);
friend class BinaryTree;
};
//*********************************************
Node::Node()
{
Lchild = Rchild = NULL;
}
Node::Node(int Data)
{
this->Data = Data;
Lchild = Rchild = NULL;
}
//**************二叉树**************
class BinaryTree
{
private:
Node* Root;
Node* p;
public:
BinaryTree();
//先序建立二叉树
Node* CreateFront();
//先序遍历二叉树
void SearchFront(Node*);
};
BinaryTree::BinaryTree()
{
Root = NULL;
}
Node* BinaryTree::CreateFront()
{
/*这个判断条件不能在这的原因:因为当p传进来的时候是一个随即地址,
这个时候那root=p就会把root赋值成随即值,所以出错
if(Root==NULL)
{
Root = p;
}*/
Node* p;
int data;
cin>>data;
if(data == -1)
{
p = NULL;
}
else
{
p = new Node(data);
/*if(Root==NULL)条件放在这也多余了
{
Root = p;
}*/
p->Lchild = CreateFront();
p->Rchild = CreateFront();
}
return p;
}
/*void BinaryTree::Creat()
{
// Root = p;
CreateFront(Root);
}*/
void BinaryTree::SearchFront(Node* q)
{
if(q != NULL)
{
cout<<q->Data<<" ";
SearchFront(q->Lchild);
SearchFront(q->Rchild);
}
}//1 2 3 -1 -1 4 5 -1 6 -1 -1 7 -1 -1 -1
int main()
{
Node* p;
BinaryTree Tree;
p = Tree.CreateFront();
Tree.SearchFront(p);
cout<<endl;
return 0;
}