题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
题目如下:
解法一:迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
int min_depth=0;
if(root==NULL) return min_depth;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int size=que.size();
min_depth++;
while(size--){
TreeNode* node=que.front();
que.pop();
if(!node->left&&!node->right) return min_depth;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return min_depth;
}
};
解法二:递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int dfs(TreeNode* root){
//思路:如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
//反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。
//最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。
if(root==NULL) return 0;
int left=dfs(root->left);//左
int right=dfs(root->right);//右
//中
if(root->left==NULL&&root->right!=NULL) return right+1;
if(root->left!=NULL&&root->right==NULL) return left+1;
//if(root->left==NULL&&root->right==NULL) return left+1;
return min(left,right)+1;
}
int minDepth(TreeNode* root) {
return dfs(root);
}
};