⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ep7_14.cpp

📁 这里有大量的c语言习题呢!真的是题海哦
💻 CPP
字号:
/*7.14  编写函数模板,用递归方法求二叉树的深度。*/

#include<iostream>
#include<cstdlib>
using namespace std;
template<typename T>class BinaryTree;
template<typename T>class Node{
	Node<T> *lchild,*rchild;
	T info;
public:
	Node(){lchild=NULL;rchild=NULL;}
	Node(T data,Node<T> *left=NULL,Node<T> *right=NULL){
		info=data;
		lchild=left;
		rchild=right;
	}
	friend class BinaryTree<T>;
};
template<typename T>class BinaryTree{
	Node<T> *root;                  //二叉树的根指针
	void Insert(const T &data,Node<T> * &b); //插入结点,参数为引用!
	void Destory(Node<T> * Current);        //删除树
	int Countdepth(Node<T> *btree);      //树深度计数
public:
	BinaryTree(){root=NULL;}						//空树构造函数
	~BinaryTree(){Destory(root);}						//析构函数
	void Creat(T* data,int n);                    //建立(排序)二叉树
	int Countdepth(){return Countdepth(root);}      //树深度计数
};
template<typename T> void BinaryTree<T>::Destory(Node<T> *Current){
	if(Current!=NULL){
		Destory(Current->lchild);
		Destory(Current->rchild);
		delete Current;  						//后序释放根结点
	}
}
template<typename T>void BinaryTree<T>::Insert(const T &data,Node<T> * &b){
	if(b==NULL){								//已到空树,插入
		b=new Node<T>(data);
		if(b==NULL){
			cout<<"空间不足"<<endl;
			exit(1);
		}
	}
	else if(data<b->info) Insert(data,b->lchild);			//小于,向左子树去查
	     else Insert(data,b->rchild);	//大于等于,向右子树去查
}
template<typename T>void BinaryTree<T>::Creat(T* data,int n){//建立一棵二叉排序树
	for(int i=0;i<n;i++) Insert(data[i],root);
}
template<typename T>int BinaryTree<T>::Countdepth(Node<T> *btree){//树深度
	int num1,num2;
	if(btree==NULL)return 0;
	else if(btree->lchild==NULL&&btree->rchild==NULL)return 1;
		else{
			num1=Countdepth(btree->lchild)+1;
			num2=Countdepth(btree->rchild)+1;
			if(num1>num2) return num1;
			else return num2;
			}
}

int main(){
	const int n=15;
	int i,a[n]={10,5,15,8,3,18,13,12,14,16,20,1,4,6,9};
	BinaryTree<int> btree;//按排序二叉树生成,共4个层次
	btree.Creat(a,n);
	cout<<"输入数据:"<<endl;
	for(i=0;i<n;i++) cout<<a[i]<<'\t';
	cout<<endl<<"树深度计数:"<<endl;
	cout<<btree.Countdepth()<<endl;    //树深度计数:4
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -