二叉链表

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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值