【LeetCode】:求二叉树最小深度问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hansionz/article/details/82085382
0.题目

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.思路

采用递归的思路求解

  • 1.如果根节点为空,则最小深度为0
  • 2.如果只有一个根节点(根节点的左右子树为空),则最小深度为1
  • 3.如果左子树为空,右子树不为空,最小深度为1+右子树的最小深度
  • 4.如果右子树为空,左子树不为空,最小深度为1+左子树的最小深度
  • 5.如果左右子树都不为空,则最小深度为1+左右子树最小深度中的较小值
2.代码实现
//求二叉树的最小深度(从根节点到最近的叶子的结点个数)
int BinaryTreeMinDepth(BTNode* root)
{
    //树为空,最小深度为0
    if (root == NULL)
        return 0;
    //只有一个根节点,最小深度为1
    if ((root->_left == NULL) && (root->_right == NULL))
        return 1;
    //左子树为空,最小深度=1+右树的最小深度
    if (root->_left == NULL)
        return 1 + BinaryTreeMinDepth(root->_right);
    //右子树为空,最小深度=1+左树的最小深度
    else if (root->_right == NULL)
        return 1 + BinaryTreeMinDepth(root->_left);
    //左右都不为空,最小深度=1+左右子树最小深度中较小值
    else
        return  BinaryTreeMinDepth(root->_left) > BinaryTreeMinDepth(root->_right) ? 1 +
BinaryTreeMinDepth(root->_right) : 1 + BinaryTreeMinDepth(root->_left);
}

对于上边代码的思路可以把3、4合并在5中,左右子树有一个为空的时候,可以直接把它当做空处理。代码可以简化为:

//求二叉树的最小深度(从根节点到最近的叶子的结点个数)
int BinaryTreeMinDepth(BTNode* root)
{
    //树为空,最小深度为0
    if (root == NULL)
        return 0;
    //只有一个根节点,最小深度为1
    if ((root->_left == NULL) && (root->_right == NULL))
        return 1;
    //直接返回最小深度=1+左右子树最小深度中较小值
    return  BinaryTreeMinDepth(root->_left) > BinaryTreeMinDepth(root->_right) ? 1 +
BinaryTreeMinDepth(root->_right) : 1 + BinaryTreeMinDepth(root->_left);
}

当然还可以换另一种写法,就是用两个变量分别保存左子树的最小深度和右子树的最小深度,最后直接比较返回就行了

int BinaryTreeMinDepth(BTNode* root)
{
    //树为空,最小深度为0
    if (root == NULL)
        return 0;
    //只有一个根节点,最小深度为1
    if ((root->_left == NULL) && (root->_right == NULL))
        return 1;
    int ml = BinaryTreeMinDepth(root->_left);//记录左子树最小深度
    int mr = BinaryTreeMinDepth(root->_right);//记录右子树最小深度

    return ml > mr ? 1 + mr : ml + 1;
}

猜你喜欢

转载自blog.csdn.net/hansionz/article/details/82085382
今日推荐