Tuesday, May 27, 2014

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.


According to the definition, the minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. The problem can be split into several cases: if it is a empty tree, depth is 0; if its left subtree is empty, its depth is its right subtree's depth plus 1; if its right left subtree is empty, its depth is its left subtree's depth plus 1; otherwise, its depth is the minimum of its left subtree's depth and its right subtree's depth plus 1.

C++ Code:

/*
 * func: min_depth
 * goal: find the minimum depth of the tree
 * @param root: root node of the tree
 * return: minimum depth
 */
int min_depth(TreeNode *root){
    if(root ==  nullptr){
        return 0;
    }else if(root->left == nullptr && root->right==nullptr){
        return 1;
    }else if(root->left == nullptr){
        return min_depth(root->right) + 1;
    }else if(root->right == nullptr){
        return min_depth(root->left) + 1;
    }else{
        return std::min(min_depth(root->left), min_depth(root->right)) + 1;
    }
}

Python Code:

# func: find the minimum depth from root node down to the nearest leaf node
# @param root: root node of the tree
# @return: minimum depth
def min_depth(root):
    if not root:
        return 0
    elif not root.left and not root.right:
        return 1
    elif not root.left:
        return min_depth(root.right)+1
    elif not root.right:
        return min_depth(root.left)+1
    else:
        return min(min_depth(root.left), min_depth(root.right)) + 1

No comments:

Post a Comment