Description
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.
Solution 1(C++)
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root->right && !root->left) return 1;
else if(root->right && root->left) return min(minDepth(root->right), minDepth(root->left))+1;
else return 1 + (root->right?minDepth(root->right):minDepth(root->left));
}
};
Solution 2(C++)
class Solution {
public:
int minDepth(TreeNode* root){
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
else
{
int l = minDepth(root->left);
int r = minDepth(root->right);
if(l == 0)
l = r;
if(r == 0)
r = l;
return min(l,r) + 1;
}
}
};
算法分析
挺简单的,就是要考虑全面,只有根节点的左右两个子节点都存在时才需要返回min(minDepth(root->right), minDepth(root->left))+1。
程序分析
略