Minimum Depth of Binary Tree

Minimum Depth of Binary TreeOct 10 '124568 / 11410

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.

 

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root)
        {
            if(root->left == NULL && root->right == NULL)
                return 1;
            else if(root->left == NULL)
                return minDepth(root->right) + 1;
            else if(root->right == NULL)
                return minDepth(root->left) + 1;
            return min(minDepth(root->left), minDepth(root->right)) + 1;
        }
        return 0;
     
    }
};


 

 

 

發佈了71 篇原創文章 · 獲贊 12 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章