1.题目:二叉树的最小深度
给定一个二叉树,找出其最小深度,最小深度是从根节点到最近叶子节点的最短路径上的节点数量
深度优先。
2.算法:深度优先搜索(DFS)
深度优先搜索算法(Depth First Search,简称DFS):一种用于遍历或搜索树或图的算法。 沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所在边都己被探寻过或者在搜寻时结点不满足条件,搜索将回溯到发现节点v的那条边的起始节点。整个进程反复进行直到所有节点都被访问为止。属于盲目搜索,最糟糕的情况算法时间复杂度为O(n)。
3.算法思想:
回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。
4.代码:
/*************************************************
作者:She001
时间:2022/8/29
题目:二叉树的最小深度
给定一个二叉树,找出其最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
深度优先、
算法:1.DFS 算法 (深度优先)
***************************************************/
#include<bits/stdc++.h>
using namespace std;
struct student
{
int a;
struct student * left;
struct student * right;
};
/*//二叉树模型
a1
a2 a3
a4 a5 a6 a7
a8
a9
*/
//算法:
int fangfa_1(struct student *root,int max)//root 树的节点,min 深度的最小值 ,max树的最大深度
{
int min1=max;
int min2=max;
if(root ==NULL)
{
return 0;
}
if(root->left==NULL && root->right==NULL)
{
return 1;
}
int min3=max;
if(root->left!=NULL)
{
min1=fangfa_1(root->left,max);
}
if(root->right!=NULL)
{
min2=fangfa_1(root->right,max);
}
int gg;
if(max > min1&& min2>min1)
{
gg=min1;
}
if(max>min2&& min1>min2)
{
gg=min2;
}
if(min1>max&& min2>max)
{
gg=max;
}
return gg+1;
}
int main()
{
//数据初始化,建立树
struct student *a1 =new struct student;
struct student *a2 =new struct student;
struct student *a3 =new struct student;
struct student *a4 =new struct student;
struct student *a5 =new struct student;
struct student *a6 =new struct student;
struct student *a7 =new struct student;
struct student *a8 =new struct student;
struct student *a9 =new struct student;
//数值的赋值
a1->a=1;
a2->a=2;
a3->a=3;
a4->a=4;
a5->a=5;
a6->a=6;
a7->a=7;
a8->a=8;
a9->a=9;
//节点的连接
a1->left=a2;
a1->right=a3;
a2->left=a4;
a2->right=a5;
a3->left=a6;
a3->right=a7;
a6->left=a8;
a8->right=a9;
//节点为空的设置
a4->left=NULL;
a4->right=NULL;
a5->left=NULL;
a5->right=NULL;
a8->left=NULL;
a9->left=NULL;
a9->right=NULL;
a6->right=NULL;
a7->left=NULL;
a7->right=NULL;
int a=fangfa_1(a1,9);
cout<<"最小深度: "<<a<<endl;
//释放空间
delete a1;
delete a2;
delete a3;
delete a4;
delete a5;
delete a6;
delete a7;
delete a8;
delete a9;
}