leetcode 111 —— Minimum Depth of Binary Tree

来源:互联网 发布:阿里云学生认证被锁 编辑:程序博客网 时间:2024/05/01 20:14

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.


思路:BFS  ,可以避免遍历整个数,当然最坏情况下是一样的

class Solution {public:int minDepth(TreeNode* root) {int level = 0;if (!root) return level;queue<TreeNode*> que;int cnt = 1;  //当前层的节点数int nex = 0;  //下一层的节点数que.push(root);while (true){level++;nex = 0;while (cnt--){   TreeNode* p = que.front();if (!p->left && !p->right)  //叶子节点return level;if (p->left){               //不能用else if,又犯傻了que.push(p->left);nex++;}if (p->right){que.push(p->right);nex++;}que.pop();}cnt = nex;}}};


0 0