#include<iostream>
#include<cassert>
using namespace std;
template<class T>
struct TreeNode
{
T data;
TreeNode<T>* left;
TreeNode<T>* right;
TreeNode(const T& x)
:data(x)
,left(NULL)
,right(NULL)
{}
};
template<class T>
class BinaryTree
{
typedef TreeNode<T> Node;
public:
BinaryTree(const T* arr,int sz,const T& invalib)//1.构造函数---前序构造二叉树
{
assert(arr);
int index=0;
_root=CreatTree(arr,sz,invalib,index);
}
~BinaryTree()//2.析构函数
{
Destroy(_root);//销毁一颗二叉树
_root=NULL;
}
int GetBinaryTreeHength()//3.求二叉树的高度
{
return _GetBinaryTreeDepth(_root);
}
protected:
Node* CreatTree(const T* arr,int sz,const T& invalib,int& index)//前序构造二叉树
{
assert(arr);
Node* root=NULL;
while (index<sz&&arr[index]!=invalib)
{
root=new Node(arr[index]);
root->left=CreatTree(arr,sz,invalib,++index);//此处index必须前置++
root->right=CreatTree(arr,sz,invalib,++index);//此处index必须前置++
}
return root;
}
----------
void Destroy(Node* root)//销毁一颗二叉树
{
//1.树为空,直接返回,无结点销毁
if (root==NULL)
{
return ;
}
//2.树只有一个结点,则销毁该节点
if (root->left==NULL&&root->right==NULL)
{
delete root;
root=NULL;
return;
}
//3.树的结点大于一个,则先销毁左子树,后销毁右子树
Destroy(root->left);
Destroy(root->right);
delete root;
root=NULL;
}
----------
int _GetBinaryTreeDepth(Node* root)//求二叉树的高度
{
//1.树为空,深度为0
if (root==NULL)
{
return 0;
}
//2.树只有一个结点,深度为1
if (root->left==NULL&&root->right==NULL)
{
return 1;
}
//3.树的结点超过一个:深度=左子树的深度和右子树深度中较大数的值+1;(1为树的根结点)
int LeftDepth=_GetBinaryTreeDepth(root->left);
int RightDepth=_GetBinaryTreeDepth(root->right);
return LeftDepth>RightDepth? LeftDepth+1:RightDepth+1;
}
protected:
Node* _root;
};
int main()
{
int arr[]={1,2,3,'#','#',4,'#','#',5,6,'#','#','#'};
int sz=sizeof(arr)/sizeof(arr[0]);
BinaryTree<int> bt(arr,sz,'#');
cout<<"二叉树的高度"<<bt.GetBinaryTreeHength()<<endl;//3
return 0;
}
求二叉树的高度/销毁一颗二叉树【递归思想】
最新推荐文章于 2022-11-25 21:14:15 发布
本文详细探讨了如何通过递归算法来计算二叉树的高度,并介绍了如何有效地销毁一棵二叉树。递归方法在解决这类问题中展现出其简洁性和效率。
摘要由CSDN通过智能技术生成