qingcheng奕  

http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/

贡献了一次runtime error,因为如果输入为{}即空的时候,出现了crash。其实这种情况也处理了,但是顺序不对,如下:

if(root->left == NULL && root->right == NULL)
            return 1;

if(root==NULL )
return 0;
如果输入是空的话,会对空->left访问left,但这是错误的。所以,应该先判断是否为空。即把两个if换个顺序就好了。

广搜,一直到有个点是叶子节点,然后返回深度。经过两道类似的题目,word ladder,求最小深度的时候,优先使用广搜。

#include <iostream>
#include <queue>

using namespace std;

struct TreeNode {
   int val;
   TreeNode *left;
   TreeNode *right;
   TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    int minDepth(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(root==NULL )
            return 0;
        if(root->left == NULL && root->right == NULL)
            return 1;


        queue<pair<TreeNode* ,int > > nodeQueue;
        nodeQueue.push(make_pair(root,1));

        int templen = 0;
        TreeNode* topNode;

        while(!nodeQueue.empty())
        {
            topNode = nodeQueue.front().first;
            templen =  nodeQueue.front().second;
            nodeQueue.pop();

            if(topNode->left == NULL && topNode->right == NULL)
                return templen;

            if(topNode->left)
                nodeQueue.push(make_pair(topNode->left,templen+1));
            if(topNode->right)
                nodeQueue.push(make_pair(topNode->right,templen+1));

        }
         
    }
};



int main()
{
    TreeNode *n0 = new TreeNode(0);
    TreeNode *n1 = new TreeNode(2);
    n0->left = n1;
    TreeNode *n2,*n3;;
    Solution mysolution;
    cout<<mysolution.minDepth(NULL);
    
    return 0;

}

 

posted on 2013-11-14 16:14  qingcheng奕  阅读(216)  评论(1编辑  收藏  举报