最近想复习一下数据结构和算法,所以就写了一个二叉树的创建和遍历
// test2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
struct tree//树结构体
{
int data;
tree *left,*right;
};
class Ctree
{
public:
static int n;
static int m;
tree *root;
Ctree()
{
root=NULL;
}
void CreateTreeNode(int a);//创建树节点;
int Sum(tree*);
void PreOrder(tree*);
void MedialOrder(tree*);
void BackOrder(tree*);
};
int Ctree::m=0;
int Ctree::n=0;
void Ctree::CreateTreeNode(int data)
{
tree *newNode=new tree;
newNode->data=data;
newNode->right=newNode->left=NULL;
if(root==NULL)
root=newNode;
else
{
tree *tail;
tree *cur=root;
while(cur!=NULL)
{ tail=cur;
if(data<cur->data)
cur=cur->left;
else
cur=cur->right;
}
if(data<tail->data)
tail->left=newNode;
else
tail->right=newNode;
}
}
int Ctree::Sum(tree *p)//计算结点数
{
if(p==NULL)
return 0;
else
return Sum(p->left)+Sum(p->right)+1;
}
void Ctree::PreOrder(tree *p)//先序遍历;
{
if(p!=NULL)
{
cout<<p->data<<endl;
PreOrder(p->left);
PreOrder(p->right);
}
}
void Ctree::MedialOrder(tree*p)//中序遍历
{
if(p!=NULL)
{
MedialOrder(p->left);
cout<<p->data<<endl;
MedialOrder(p->right);
}
}
void Ctree::BackOrder(tree *p)//后序遍历
{
if(p!=NULL)
{
BackOrder(p->left);
BackOrder(p->right);
cout<<p->data<<endl;
}
}
int main(int argc, char* argv[])
{
Ctree *T=new Ctree();
T->CreateTreeNode(10);//根结点
T->CreateTreeNode(7);
T->CreateTreeNode(8);
T->CreateTreeNode(11);
T->CreateTreeNode(9);
T->CreateTreeNode(6);
cout<<"结点数:"<<T->Sum(T->root)<<endl;
cout<<"先序遍历:"<<endl;
T->PreOrder(T->root);
cout<<"中序遍历:"<<endl;
T->MedialOrder(T->root);
cout<<"后序遍历:"<<endl;
T->BackOrder(T->root);
getchar();
return 0;
}
输出结果如下:
