題目描述
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.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
題目思路
- 思路一、二叉樹的層次遍歷,到某一層某個(gè)節(jié)點(diǎn)時(shí),判斷該節(jié)點(diǎn)是否左右子孩子為空,若為空則直接返回層數(shù)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL){
return 0;
}
int minlevel = 1;
int current = 1;
int next = 0;
deque<TreeNode *> que;
que.push_back(root);
TreeNode *temp;
while(!que.empty()){
temp = que.front();
que.pop_front();
current -= 1;
if(temp->left==NULL && temp->right == NULL){
return minlevel;
}
if(temp->left != NULL){
que.push_back(temp->left);
next += 1;
}
if(temp->right != NULL){
que.push_back(temp->right);
next += 1;
}
if(current == 0){
current = next;
next = 0;
minlevel += 1;
}
}
return 0; // 這句話永遠(yuǎn)也不會(huì)執(zhí)行的
}
};
