Saturday, April 20, 2013

Leetcode: Minimum Depth of Binary Tree in C++




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.
Solution:
void helper(TreeNode *root, int& minD, int cur)
    {
        if(root->left==NULL&&root->right==NULL)
        {
            if(cur<minD)
            minD = cur;
            return;
        }
        if(root->left)
        helper(root->left, minD,cur+1);
        if(root->right)
        helper(root->right, minD,cur+1);
    }
    int minDepth(TreeNode *root) {
       if(!root)
       return 0;
       int minD=INT_MAX;
       helper(root, minD, 1);
       return minD;
    }

No comments:

Post a Comment