题目:
二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
第一次做的时候是11.11, 当时做了好一会,用的层次遍历,今天重新刷了一遍,完全凭感觉,递归就做出来了。思路也不是很清晰,就是ac了
层次遍历
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode *> qu;
if(!root){
return 0;
}
if(!root->left && !root->right){
return 1;
}
qu.push(root);
int depth=0;
while(qu.size()>0){
int qs=qu.size();
depth++;
for(int i=0;i<qs;i++){
TreeNode *p=qu.front();
qu.pop();
if(p->left){
qu.push(p->left);
}
if(p->right){
qu.push(p->right);
}
if(!p->left && !p->right){
return depth;
}
}
}
return 0;
}
};
递归
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root){
return 0;
}
if(!root->left){
return 1+minDepth(root->right);
}
if(!root->right){
return 1+minDepth(root->left);
}
return 1+min(minDepth(root->left),minDepth(root->right));
}
};