思路:
要求找离根节点最近的叶子节点,那么就DFS遍历下去,定义一个数来记录当前的节点到最近的叶子节点的距离,然后每次递归得到的距离都和这个最近距离比较,如果小就更新。
代码:
/**
* 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) {
if(root==nullptr) return 0;
if(root->left==nullptr&&root->right==nullptr) return 1;
int min_depth=INT_MAX;
if(root->left){
min_depth=min(minDepth(root->left),min_depth);
}
if(root->right){
min_depth=min(minDepth(root->right),min_depth);
}
return min_depth+1;
}
};
通过BFS找到的第一个叶子节点就是最近的,可以直接返回深度。
代码:
/**
* 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) {
if(root==nullptr) return 0;
queue<pair<TreeNode*,int>> q;
q.emplace(root,1);
while(!q.empty()){
TreeNode* node = q.front().first;
int depth=q.front().second;
q.pop();
if(node->left==nullptr&&node->right==nullptr) return depth;
if(node->left) q.emplace(node->left,depth+1);
if(node->right)q.emplace(node->right,depth+1);
}
return 0;
}
};
111. Minimum Depth of Binary Tree
原文:https://www.cnblogs.com/Mrsdwang/p/14664226.html