[leetcode 111] Minimum Depth of Binary Tree

2 篇文章 0 订阅
2 篇文章 0 订阅

题目要求:

Minimum Depth of Binary Tree

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.

最近一直在leetcode上做树相关的题目,自我感觉一直做的不好,或者说思路很不清晰的最主要原因是对于递归的运行机制理解得不透彻,通过这一题有了更近一步的认识。“在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储。”

代码一:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int min(int a, int b)
{
    if (a < b)
        return a;
    else
        return b;
}

int minDepth(struct TreeNode* root) {
    
    if (root == 0)
        return 0;
    if( root->left )                  //判断左子树存在
    {
        if( root->right )              //判断右子树存在
        {
            return min(minDepth(root->left), minDepth(root->right)) + 1;   
        }                              //当左右子树都存在的时候,在此次设置递归函数断点
        else
            return minDepth(root->left) + 1; //只存在左子树的时候,设置在此设置递归函数断点
    }
    else if( root->right )
    {
        return minDepth(root->right) + 1; //只存在右子树的时候,设置在此设置递归函数断点
    }  
    else
        return 1;                         //左右子树都为空,返回1 
}
代码参考自:http://www.julyedu.com/video/play/id/32


代码二:


<span style="font-size:14px;">/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


int minDepth(struct TreeNode* root)
{
    int left, right;  //一开始把这两个变量设置为全局变量的时候出现RA
    if(root == 0)
        return 0;
    if(root->left == 0 && root->right == 0)
        return 1;
    left = minDepth(root->left) + 1; //左子树设置断点递归
    right = minDepth(root->right) + 1;//右子树设置断点递归
    if(left == 1)
        left = INT_MAX;   //当左子树为空时,将它设置为无限大量,剔除干扰       
    if(right == 1)
        right = INT_MAX;  //同上
    return left < right ? left : right; //返回小的
}
注:INT_MAX 头文件:#include <limits.h>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值