LeetCode 111 Minimum Depth of Binary Tree

标签: 宽度优先搜索 LeetCode 发布于:2022-02-22 19:04:19 编辑于:2022-02-22 20:10:27 浏览量:946

概述

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

宽度优先搜索

while 循环 + 队列,同时记录节点指针和对应深度。

被 LeetCode 用一个空指针偷袭了,我没防住。。。

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        queue<pair<TreeNode*, int>> q;
        q.push({root, 1});
        while (!q.empty()) {
            auto c = q.front();
            q.pop();
            if (!c.first->left && !c.first->right) {
                return c.second;
            }
            if (c.first->left) {
                q.push({c.first->left, c.second + 1});
            }
            if (c.first->right) {
                q.push({c.first->right, c.second + 1});
            }            
        }
        return -1;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/