Monday, November 25, 2013

LeetCode Problem : Minimum Depth of Binary Tree

Problem


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.

Code

int minDepth(TreeNode *root) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(!root)
        return 0;
    if(root->left == 0 && root->right == 0)
        return 1;
    if(root->left == 0)
        return 1 + minDepth(root->right);
    if(root->right == 0)
        return 1 + minDepth(root->left);
    return ( 1 + min(minDepth(root->left),minDepth(root->right)));
}

No comments:

Post a Comment