leetcode 31: 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.

1. different from maximum depth. if a node only has one child, the depth will be 1 + child depth.

/**

 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return minRec(root);
    }
    
    int minRec( TreeNode * root) {
        if(!root) return 0;
        
        int left = minRec( root->left);
        int right = minRec( root->right);
        
        if(left && right) return 1 + min(left, right);
        if(left || right) return 1+left+right;
        return 1;
    }
};


posted @ 2013-01-11 08:25  西施豆腐渣  阅读(143)  评论(0编辑  收藏  举报