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.

题目描写叙述:

             求二叉树的最小深度。和求二叉树的最大深度有些差别,细致看了别人的简洁代码。

代码实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==0)
        {
            return 0;
        }
        int left=minDepth(root->left);
        int right=minDepth(root->right);
        if(left==0)
        {
            return right+1;
        }
        else if(right==0)
        {
            return left+1;
        }
        else
        {
            return min(left,right)+1;
        }
    }
};


posted @ 2017-06-13 16:05  wzjhoutai  阅读(150)  评论(0编辑  收藏  举报