LeetCode 111 Minimum Depth of Binary Tree BFS
阿新 • • 發佈:2022-05-28
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; } };