[LeetCode] 111. Minimum Depth of Binary Tree

来源:互联网 发布:造粉神器软件 编辑:程序博客网 时间:2024/05/22 11:38

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.

// BFSclass Solution {public:    int minDepth(TreeNode* root) {        if (root == nullptr) return 0;        int Depth = 1;        queue<TreeNode *> q;        q.push(root);        q.push(nullptr);        while (!q.empty()) {            TreeNode *ptn = q.front();            q.pop();            if (ptn == nullptr) {                Depth++;                q.push(nullptr);                continue;            }            if (ptn->left == nullptr && ptn->right == nullptr)                break;            if (ptn->left)                q.push(ptn->left);            if (ptn->right)                q.push(ptn->right);        }        return Depth;    }};
原创粉丝点击