LeetCode - Minimum Depth of Binary Tree

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.

int depth(TreeNode* root, int level) {
    if (NULL == root) {
        return level - 1;
    }

    if ((NULL == root->left) && (NULL == root->right)) {
        return level;
    } else if (NULL == root->left) {
        return depth(root->right, level + 1);
    } else if (NULL == root->right) {
        return depth(root->left, level + 1);
    } else {
        int l = depth(root->left, level + 1);
        int r = depth(root->right, level + 1);
        return l < r ? l : r;
    }
}

int minDepth(TreeNode *root) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    return depth(root, 1);
}


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