xinyu04

导航

LeetCode 111 Minimum Depth of Binary Tree BFS

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.

Note: A leaf is a node with no children.

Solution

\(queue\) 将元素压入队列,然后每次循环该层的所有元素,如果该元素没有左右子节点,则直接返回当前深度

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int ans = 999999;
    queue<TreeNode*> q;
    
    
public:
    int minDepth(TreeNode* root) {
        if(!root)return 0;
        if(!root->right && !root->left)return 1;
        q.push(root);
        int cur_dep = 1;
        while(!q.empty()){
            int n = q.size();
            for(int i=0;i<n;i++){
                TreeNode *rt = q.front();
                if(rt->left)q.push(rt->left);
                if(rt->right)q.push(rt->right);
                if(!rt->right && !rt->left)return cur_dep;
                q.pop();
            }
            cur_dep+=1;
        }
        return cur_dep;
    }
};

posted on 2022-05-28 14:51  Blackzxy  阅读(14)  评论(0编辑  收藏  举报