111. Minimum Depth of Binary Tree

来源:互联网 发布:mac 搭建gitlab服务器 编辑:程序博客网 时间:2024/06/01 07:34
问题描述;

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.

解题思路:
直接求最短路径就是左右子树depth相比较就行了。
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL) return 0;
        else if(root->left==NULL&&root->right==NULL)
            return 1;
        else
        {
            int left_depth,right_depth;
            if(root->left)
                left_depth=minDepth(root->left);
            else
                left_depth=INT_MAX;
            if(root->right)
                right_depth=minDepth(root->right);
            else
                right_depth=INT_MAX;
            return min(left_depth,right_depth)+1;
        }
    }
};
原创粉丝点击