求二叉树最小层数

int minDepth(TreeNode* root) {
    if (root == nullptr) {
        return 0;
    }
    
    constexpr int MAX_DEPTH    = INT16_MAX;
    constexpr int initLayerNum = 1;
    
    function<int(TreeNode*&, int)> check;
    check = [&](TreeNode*& node, int num)
    {
        if (node == nullptr) {
            return MAX_DEPTH;
        }
        
        if (node->left == nullptr && node->right == nullptr){
            return num;
        }
        else{
            return min(check(node->left, num + 1), check(node->right, num + 1));
        }
    };
    
    return check(root, initLayerNum);
}

 

posted @ 2015-08-11 17:23  wu_overflow  阅读(288)  评论(0编辑  收藏  举报