给定一个二叉树,找到它的最小深度。

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

给定一个二叉树,找到它的最小深度。最小深度是根节点到最近叶子节点路径上的节点数。

第一种是我的想法,采用递归的想法。

1、最开始想到每一个父亲节点的最小深度都是其子节点最小深度数加一。

2、当本节点为空时,返回深度0;

3、当本节点的左孩子和右孩子为空的时候,返回深度1;

4、当左孩子为空,右孩子非空时,返回右孩子的最小深度加一

5、当右孩子为空,左孩子非空的时候,返回左孩子的最小深度加一

6、最后一种为左右孩子都非空的情况,返回左右孩子最小深度的小值加一。

class Solution {

public:

int min(int a,int b)

{

if(a>=b)

return b;

else

return a;

}

int run(TreeNode *root) {

if(root == nullptr)

{ return 0;}

if(root->left == nullptr && root->right==nullptr)

{return 1;}

if(root->left !=nullptr && root->right == nullptr)

{return run(root->left)+1;}

if(root->left ==nullptr && root->right != nullptr)

{return run(root->right)+1;}

return min(run(root->left),run(root->right))+1;

}

注意:最开始的时候在函数中连续写了五个if语句,编译的时候会报错!!!

用gcc编译一个程序的时候出现这样的警告:

warning: control reaches end of non-void function

它的意思是:控制到达非void函数的结尾。就是说你的一些本应带有返回值的函数到达结尾后可能并没有返回任何值。这时候,最好检查一下是否每个控制流都会有返回值。

反思:每一个递归函数一定要在if语句之外有一个return语句,这样才不会出现上面的报错。原因可能时计算机在执行if时是随机选择语句进行执行的。

猜你喜欢

转载自blog.csdn.net/qq_22152499/article/details/82867295
今日推荐