C++ 二叉树求最大深度

通过一个递归即可轻松实现,通过h记录访问结点所在的深度,max_height记录所到达的最大深度。

核心代码如下:

int max_height = -1;

void GetBTHeight(BTNode *bt,int h){//获取二叉树的高度 
	if(bt == nullptr || h < 1 )
		return ;
	if(bt->m_pLeft == nullptr && bt->m_pRight ==nullptr)
	{
		max_height = max(max_height,h);
		return ;
	}
	GetBTHeight(bt->m_pLeft,h+1);
	GetBTHeight(bt->m_pRight,h+1);
}

程序完整代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
 
typedef struct BinaryTreeNode{
	int value;
	BinaryTreeNode *m_pLeft;
	BinaryTreeNode *m_pRight;
}BTNode;

int max_height = -1;
 
void addBTNode(BTNode *&myBT,int val);//添加节点 
void createBT(BTNode *&BT,int arr[],int n);//创建二叉排序树,通过*&来改变指针的值

void GetBTHeight(BTNode *bt,int index);//获取二叉树的高度 
 
void midorder_showBT(BTNode *myBT);//中序遍历打印,如果是二叉排序树,打印结果与单调递增数组一样 
 
int main(){
	
	BTNode *myBT = nullptr;
	
	int arr[10] = {314,426,12,78,143,8,21,14,9,314};
	createBT(myBT,arr,10);
	
	midorder_showBT(myBT);
	cout<<endl;
	
	GetBTHeight(myBT,1);
	cout<<"二叉排序的最大高度为:"<<max_height<<endl;
	
	return 0;
}

void createBT(BTNode *&BT,int arr[],int n){
	BT = nullptr;
	for(int i=0;i<n;i++)
		addBTNode(BT,arr[i]);	
}

void GetBTHeight(BTNode *bt,int h){//获取二叉树的高度 
	if(bt == nullptr || h < 1 )
		return ;
	if(bt->m_pLeft == nullptr && bt->m_pRight ==nullptr)
	{
		max_height = max(max_height,h);
		return ;
	}
	GetBTHeight(bt->m_pLeft,h+1);
	GetBTHeight(bt->m_pRight,h+1);
}
 


void addBTNode(BTNode *&myBT,int val){
	if(myBT == nullptr){
		myBT = new BinaryTreeNode();
		myBT->value = val;
		myBT->m_pLeft = nullptr;
		myBT->m_pRight = nullptr;
		return;	
	}
		
	if(val == myBT->value){
		return;
	}
	else if(val < myBT->value){
		addBTNode(myBT->m_pLeft,val);
	}
	else{
		addBTNode(myBT->m_pRight,val);
	}			
}

 
void midorder_showBT(BTNode *myBT){//中序遍历打印 {
	if(myBT == nullptr )
		return;
	
	midorder_showBT(myBT->m_pLeft);
	cout<<myBT->value<<" ";
	midorder_showBT(myBT->m_pRight);
}

运行结果如下:


猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/80948995