题目描述
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.
题目思路
- 思路一、二叉树的层次遍历,到某一层某个节点时,判断该节点是否左右子孩子为空,若为空则直接返回层数
/**
* 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; // 这句话永远也不会执行的
}
};