Leetcode 111. Minimum Depth of Binary Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Minimum Depth of Binary Tree

2. Solution

  • Version 1
/**
 * Definition for a binary tree node.
 * 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) {
            return 0;
        }
        int minDepth = INT_MAX;
        traverse(root, 0, minDepth);
        return minDepth;
    }

private:
    void traverse(TreeNode* root, int depth, int& minDepth) {
       if(!root) {
           return;
       }
       depth++;
       if(!root->left && !root->right && depth < minDepth) {
           minDepth = depth;
           return;
       }
       traverse(root->left, depth, minDepth);
       traverse(root->right, depth, minDepth);
    }
};
  • Version 2
/**
 * Definition for a binary tree node.
 * 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) {
            return 0;
        }
        if(!root->left) {
            return minDepth(root->right) + 1;
        }
        if(!root->right) {
            return minDepth(root->left) + 1;
        }
        return min(minDepth(root->left), minDepth(root->right)) + 1;
    }
};

Reference

  1. https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 父亲的眼睛和嘴角突然流出一条条血来。亲戚走上来拉住我,不让我骂,她说,人死后灵魂还在身体里的,“你这样闹,他走不开...
    prismapaul阅读 3,051评论 0 0
  • 绝大多数人都有这样的感觉,工作的时候,精力不集中效率低;休息的时候,即便睡了很长时间仍旧乏力,究其根本原因,是方法...
    艾问才会赢阅读 2,744评论 0 4
  • 慎独,今天老婆他们去了杭州,我表现的还是不够尽如人意。 不过好的是我在改变,需要变得更加的符合规律,很多事情的客观...
    亮亮_412阅读 1,033评论 0 0
  • C++为类中提供类成员的初始化列表 类对象的构造顺序是这样的:1.分配内存,调用构造函数时,隐式/显示的初始化各数...
    安然_fc00阅读 5,673评论 1 1