问题描述;
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.
解题思路:
直接求最短路径就是左右子树depth相比较就行了。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
else if(root->left==NULL&&root->right==NULL)
return 1;
else
{
int left_depth,right_depth;
if(root->left)
left_depth=minDepth(root->left);
else
left_depth=INT_MAX;
if(root->right)
right_depth=minDepth(root->right);
else
right_depth=INT_MAX;
return min(left_depth,right_depth)+1;
}
}
};
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
else if(root->left==NULL&&root->right==NULL)
return 1;
else
{
int left_depth,right_depth;
if(root->left)
left_depth=minDepth(root->left);
else
left_depth=INT_MAX;
if(root->right)
right_depth=minDepth(root->right);
else
right_depth=INT_MAX;
return min(left_depth,right_depth)+1;
}
}
};