c++二叉树的建立与遍历

刚学数据机构没多久,学校又是讲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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值