题目链接
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
题解一
- 递归解法
- 我写的
- 说明详见注释
// Problem: LeetCode 111
// URL: https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
// Tags: Tree Recursion DFS
// Difficulty: Easy
#include <iostream>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};
class Solution{
private:
int min=INT_MAX;
// 深度优先遍历,在过程中记录最小路径
void dfs(TreeNode* root, int level){
if(root==nullptr)
return;
level += 1;
if(root->left==nullptr && root->right==nullptr && level < this->min)
this->min = level;
dfs(root->left, level);
dfs(root->right, level);
}
public:
int minDepth(TreeNode* root){
// 空树则最小路径为0
if(root==nullptr)
return 0;
dfs(root, 0);
return this->min;
}
};
题解二
- 递归解法
- 参考了官方的题解
- 说明详见代码注释,感觉有些地方比较不符合人的思维逻辑
// Problem: LeetCode 111
// URL: https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
// Tags: Tree Recursion DFS
// Difficulty: Easy
#include <iostream>
#include <algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};
class Solution{
public:
int minDepth(TreeNode* root){
// 空树则最小路径为0
if(root==nullptr)
return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
// 如果子树中有空树, 则该树的最小深度等于子树深度之和+1
if(left==0 || right==0)
return left+right+1;
// 如果子树都不为空,则该树的最小深度等于子树深度较小值+1
return min(left, right)+1;
}
};
作者:@臭咸鱼
转载请注明出处:https://www.cnblogs.com/chouxianyu/
欢迎讨论和交流!