[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.

思考:考虑[1,2]这种情况,返回树最低高度为2。所以分两种情况,有一棵子树不在时,返回另一棵子树树高+1,否则返回矮子树高+1.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int ret;
public:
    int DFS(TreeNode *root)
    {
        if(root==NULL) return 0;
        else if(!root->left&&!root->right) return 1;
        int height1=DFS(root->left);
        int height2=DFS(root->right);
        if(height1==0) return height2+1;
        if(height2==0) return height1+1;
        return min(height1,height2)+1;
    }
    int minDepth(TreeNode *root) {
        if(root==NULL) return 0;
        ret=DFS(root);
        return ret;
    }
};

  

posted @ 2013-12-05 12:35  七年之后  阅读(159)  评论(0编辑  收藏  举报