Leetcode 111. Minimum Depth of Binary Tree

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

1. Description

《Leetcode 111. Minimum Depth of Binary Tree》 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/
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/d5281ef80940
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞