題目:
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.
分析:
要得出二叉樹中所有從根到葉子節點路徑中,經過結點最少路徑上的節點數。採用二叉樹的層序遍歷思想,每遍歷一層,高度加一,只要遇到葉子節點,就終止,並返回當前層數。
代碼:
class Solution {
public:
int minDepth(TreeNode* root) {
deque<TreeNode*> store;
int left_num;
int res = 0;
if(!root)
return res;
store.push_back(root);
while(!store.empty()) {
res++;
vector<int> res_t;
left_num = store.size();
while(left_num-- > 0) {
const TreeNode* tmp = store.front();
if(!tmp->left&&!tmp->right)
return res;
store.pop_front();
res_t.push_back(tmp->val);
if(tmp->left)
store.push_back(tmp->left);
if(tmp->right)
store.push_back(tmp->right);
}
}
}
};