二叉树

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

struct Node{
	int data;
	Node *left,*right;
	};

class Btree{
private:
	Node *root;
public:
	Btree(){
		root=NULL;
		}
	Btree(int x[],int n);
	void create(int x[],int n);
	void insert(int x);
	void preOrder();
	void inOrder();
	void postOrder();
	int getNodeCount();
	int getLeafCount();
private:
	void preOrder1(Node *node);
	void inOrder1(Node *node);
	void postOrder1(Node *node);
	int getNodeCount1(Node *node);
	int getLeafCount1(Node *node);
	};

Btree::Btree(int x[],int n){
	root=NULL;
	create(x,n);
	}
void Btree::insert(int x){
	Node *s=new Node;
	s->data=x;
	s->left=s->right=NULL;
	if(root==NULL)
		root=s;
	else{
		Node *p,*cur=root;
		do{
			p=cur;
			if(cur->data==x)
				return;
			else if(cur->data>x)
				cur=cur->left;
			else
				cur=cur->right;
			}while(cur!=NULL);
		if(p->data>x)
			p->left=s;
		else
			p->right=s;
		}
	}

void Btree::create(int x[],int n){
	for(int i=0;i<n;i++)
		insert(x[i]);
	}
void Btree::preOrder(){
	preOrder1(root);
	}
void Btree::inOrder(){
	inOrder1(root);
	}
void Btree::postOrder(){
	postOrder1(root);
	}
void Btree::preOrder1(Node *node){
	if(node!=NULL){
		cout<<node->data<<" ";
		preOrder1(node->left);
		preOrder1(node->right);
		}
	}
void Btree::inOrder1(Node *node){
	if(node!=NULL){
		inOrder1(node->left);
		cout<<node->data<<" ";
		inOrder1(node->right);
		}
	}
void Btree::postOrder1(Node *node){
	if(node!=NULL){
		postOrder1(node->left);
		postOrder1(node->right);
		cout<<node->data<<" ";
		}
	}

int Btree::getNodeCount(){
	return getNodeCount1(root);
	}
int Btree::getNodeCount1(Node *node){
	if(node==NULL)
		return 0;
	return getNodeCount1(node->left)+getNodeCount1(node->right)+1;
	}
int Btree::getLeafCount(){
	return getLeafCount1(root);
	}
int Btree::getLeafCount1(Node *node){
	if(node==NULL)
		return 0;
	if(node->left==NULL&&node->right==NULL)
		return 1;
	return getLeafCount1(node->left)+getLeafCount1(node->right);
	}



void main(){
	int data[10];
	srand(time(NULL));
	for(int i=0;i<10;i++)
		data[i]=rand()%100+1;

	//打印原始数据
	cout<<"original data:";
	for(int i=0;i<10;i++)
		cout<<data[i]<<" ";
	cout<<endl;
		
	Btree btree(data,10);
	cout<<"preOrder:";
	btree.preOrder();
	cout<<endl;

	cout<<"inOrder:";
	btree.inOrder();
	cout<<endl;

	cout<<"postOrder:";
	btree.postOrder();
	cout<<endl;

	cout<<"total node count:";
	cout<<btree.getNodeCount()<<endl;

	cout<<"total leaf count:";
	cout<<btree.getLeafCount()<<endl;
	

	cout<<endl;
	system("pause");
	}


欢迎加QQ:算法交流群(538117042)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值