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.
2. 广度优先(c++)
class Solution { public: int run(TreeNode *root) { //合法性检验 if(!root) return 0; queue<TreeNode*> Queue; TreeNode* last = root; TreeNode* now=NULL; unsigned int level=1,size=0; //入队 Queue.push(root); while(Queue.size()) { //队首元素赋值给now now = Queue.front(); //出队 Queue.pop(); size = Queue.size(); //若左子树不空则入队 if(now->left) Queue.push(now->left); //若右子树不空,入队 if(now->right) Queue.push(now->right); //Queue.size返回值类型为unsigned int //若队列长度未改变则是到了叶子节点 if(Queue.size()-size==0) break; //若该节点出入过队列则,不是叶子结点 if(last == now) { level++; if(Queue.size()) last = Queue.back(); } } return level; } };