1.实验所设计的知识点
(1)定义二叉树的链式存储结构
(2)建立一颗二叉链表表示的二叉树
(3)对其进行前序,中序,后序输出
2.程序源码
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
using namespace std;
class BinaryNode //节点类
{
public:
int data;
BinaryNode *l;
BinaryNode *r;
BinaryNode( int data , BinaryNode *l , BinaryNode *r )//构造函数
{
this->data=data;
this->l=l;
this->r=r;
}
};
BinaryNode *root;
bool contains(int x ,BinaryNode *t)
{
if(t==NULL)
return false;//根节点为零,返回查找不到
else if(x<t->data)//与当前节点数据域比较,小则找左节点,大则找右节点,递归调用
return contains(x,t->l);
else if(t->data<x)
return contains(x,t->r);
else
return true;
}
void insert(int x ,BinaryNode * &t)
{
if(t==NULL)//插入过程与查找过程类似,从根节点开始比较,
t=new BinaryNode(x,NULL,NULL);//调用构造函数
else if(x<t->data)
insert(x,t->l);//插入到X的左子树
else if(t->data<x)
insert(x,t->r);//插入到X的右子树
}
BinaryNode *findMax(BinaryNode *t)//一直从右子树开始找
{
if(t!=NULL)
while(t->r!=NULL)
t=t->r;
return t;
}
void printall(BinaryNode *&t)
{
if (t==NULL)
return;
else
{cout<<t->data<<endl;
printall(t->l);
printall(t->r);
}
}
int main(int argc, char* argv[])
{
//int i=1,n=1;
BinaryNode *t , *max ;
t=NULL;
insert(9, t);
insert(86, t);
insert(4, t);
insert(44, t);
insert(3, t);
max=findMax(t);
cout<<"最大值是"<<max->data<<endl;
if( contains(4 ,t))
cout<<"查找在树内"<<endl;
else
cout<<"查找值不在树内"<<endl;
cout<<"节点内容"<<endl;
printall(t);
return 0;
}