Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
/**
* Definition for binary tree
* 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 == NULL)
return 0;
else if(root->left == NULL && root->right == NULL)
return 1;
else if(root->left != NULL && root->right == NULL)
return minDepth(root->left)+1;
else if(root->left == NULL && root->right != NULL)
return minDepth(root->right)+1;
else
return min(minDepth(root->left), minDepth(root->right))+1;
}
private:
int min(const int& a, const int& b) {
return a < b? a : b;
}
};
第二次写这个类:
/**
* Definition for binary tree
* 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 == NULL)
return 0;
else if(root->left == NULL)
return minDepth(root->right)+1;
else if(root->right == NULL)
return minDepth(root->left)+1;
else
return min(minDepth(root->left), minDepth(root->right))+1;
}
private:
int min(const int& a, const int& b) {
return a < b? a : b;
}
};
本文介绍如何通过递归的方式找到给定二叉树的最小深度,即从根节点到最近叶子节点的最短路径长度。代码示例中包含了两种实现方式,详细解释了每个步骤和关键逻辑。
323

被折叠的 条评论
为什么被折叠?



