前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Minimum Depth of Binary Tree

Leetcode: Minimum Depth of Binary Tree

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 17:27:12
3460
发布2019-01-22 17:27:12
举报

题目: 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.

思路分析: 求二叉树的最小深度。二叉树多用迭代。

C++示例代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution
{
public:
    int minDepth(TreeNode *root)
    {
        if (root == NULL)
        {
            return 0;
        }

        //leftDepth=0,rightDepth=0直接返回1
        if (root->left == NULL && root->right == NULL)
        {
            return 1;
        }

        int leftDepth = minDepth(root->left);
        int rightDepth = minDepth(root->right);

        //这里leftDepth和rightDepth不可能同时为0
        if (leftDepth == 0)
        {
            return rightDepth + 1;
        }
        else if (rightDepth == 0)
        {
            return leftDepth + 1;
        }
        else
        {
            return min(leftDepth, rightDepth) + 1;
        }
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年03月09日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档