求二叉树的最小深度
一、求二叉树的最小深度
在前文二叉链表的实现的基础上添加一个求二叉树的最小深度的方法:SmallestDepth。二叉树的最小深度指的是从根节点到最近的叶子结点的距离。
当二叉树为空时,返回0;
当二叉树的左子树为空时返回右子树的最小深度+1;
当二叉树的右子树为空时返回左子树的深度+1;
当二叉树的左右子树都不为空时返回左右子树最小深度较小的值+1;
二、求二叉树最小深度实现
1.SmallestDepth类文件
/*位于BiTree.h文件中*/
template <class ElemType>
struct BiNode{
ElemType data;
BiNode<ElemType> *lchild,*rchild;
};
template <class ElemType>
class BiTree{
public:
BiTree() {root=Create(root);}//构造函数,建立一颗二叉树
~BiTree() {Release(root);}//析构函数,释放各个节点
int SmallestDepth(){return SmallestDepth(root);} ;
private:
int BiTreeCountNode;
BiNode<ElemType>* root;
BiNode<ElemType>* Create(BiNode<ElemType>* bt) ;
void Release(BiNode<ElemType>* bt);
int SmallestDepth(BiNode<ElemType> * bt);
};
2.SmallestDepth类方法
/*位于BiTree.cpp文件中*/
template <class ElemType>
int BiTree<ElemType>::SmallestDepth(BiNode<ElemType> * bt)
{
if(bt==NULL)
return 0;
if(bt->lchild==NULL)
return SmallestDepth(bt->rchild)+1;
if(bt->rchild==NULL)
return SmallestDepth(bt->lchild)+1;
int m = SmallestDepth(bt->lchild)+1;
int n = SmallestDepth(bt->rchild)+1;
return m<n?m:n;
}
三、求二叉树最小深度代码测试
1.主函数
#include <iostream>
#include "BiTree.h"
#include "BiTree.cpp"
using namespace std;
int main() {
BiTree<char> T;
cout<<"二叉树最小深度:"<<T.SmallestDepth()<<endl;
return 1;
}
2.输出结果
按照下面这个扩展二叉树的顺序,依次输入:A B # # C D # # #。
请输入创建一颗二叉树的结点数:
A
请输入创建一颗二叉树的结点数:
B
请输入创建一颗二叉树的结点数:
#
请输入创建一颗二叉树的结点数:
#
请输入创建一颗二叉树的结点数:
C
请输入创建一颗二叉树的结点数:
D
请输入创建一颗二叉树的结点数:
#
请输入创建一颗二叉树的结点数:
#
请输入创建一颗二叉树的结点数:
#
二叉树最小深度:2
四、源代码获取(免积分)
源代码地址