题目链接:
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
难度:简单
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 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==nullptr){
return 0;
}
return dfs(root,1);
}
int dfs(TreeNode* root,int d){
if(root==nullptr){
return d-1;
}
if(root->left==nullptr&&root->right==nullptr){
return d;
}else if(root->left!=nullptr&&root->right!=nullptr){
int left=dfs(root->left,d+1);
int right=dfs(root->right,d+1);
return min(left,right);
}else{
int left=dfs(root->left,d+1);
int right=dfs(root->right,d+1);
return max(left,right);
}
}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==nullptr){
return 0;
}
queue<pair<TreeNode*,int>> que;
que.emplace(root,1);
while(!que.empty()){
auto a=que.front();
TreeNode* node=a.first;
int depth=a.second;
que.pop();
if(node->left==nullptr&&node->right==nullptr){
return depth;
}
if(node->left!=nullptr){
que.emplace(node->left,depth+1);
}
if(node->right!=nullptr){
que.emplace(node->right,depth+1);
}
}
return 0;
}
};