104.二叉树最小深度

题目:[https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/]
思路:逐层遍历,当某层有子节点时,当前层即是最小深度
代码:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root==NULL) {//空值判断
            return 0;
        }
        pair<int,TreeNode*> sore(1,root);//pair类型记录当前层数和指针
        deque<pair<int, TreeNode*>> que;//pair对象的队列
        que.push_back(sore);//队列初始值
        while (!que.empty()) {//队列为空吗
            auto &pin=que.front();
            if (pin.second!=NULL) {//队首所pair的指节点是否为为空,为空则直接跳过避免未定义操作
                if (pin.second->left==NULL&&pin.second->right==NULL) {//节点左右皆为空,找到子节点
                    break;
                }
                que.push_back({pin.first+1,pin.second->left});//将左右孩子加入队列,并使层数+1;
                que.push_back({pin.first+1,pin.second->right});
            }
            que.pop_front();
        }
        return que.front().first;
    }
};

讨论区[https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/36071/BFS-C++-8ms-Beats-99.94-submissions]
讨论区优秀代码

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        queue<TreeNode*> tmp;
        tmp.push(root);
        int i = 1;
        while (true) {
            int size = tmp.size();//更新size大小,通过对size大小对控制,保证逐层访问
            for (int j = 0; j < size; j++) {
                TreeNode *p = tmp.front();
                tmp.pop();//推出已用队列
                if (p->left == NULL && p->right == NULL) {
                    return i;//遇到子节点,返回当前层数
                }
                else if (p->left == NULL) {
                    tmp.push(p->right);
                }
                else if (p->right == NULL) {
                    tmp.push(p->left);
                }
                else {
                    tmp.push(p->left);
                    tmp.push(p->right);
                }
            }
            i++;//当层访问完毕,没遇到子节点,层数+1
        }
    }
};

反思:bfs可以通过控制队列大小当方式来记录当前当层数

posted @ 2018-09-20 17:52  Kipper  阅读(107)  评论(0编辑  收藏  举报