【问题描述】
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;
-
* struct TreeNode *left;
-
* struct TreeNode *right;
-
* };
-
*/
-
static int min(int a, int b)
-
{
-
if(a<=b)
-
{
-
return a;
-
}
-
else
-
{
-
return b;
-
}
-
}
-
-
static int minDepthDfs(struct TreeNode *root, bool hasbrother)
-
{
-
if (!root)
-
{
-
return hasbrother ? INT_MAX : 0;
-
}
-
-
return 1 + min(minDepthDfs(root->left, root->right != NULL),
-
minDepthDfs(root->right, root->left != NULL));
-
}
-
-
int minDepth(struct TreeNode *root) {
-
return minDepthDfs(root, false);
-
}
阅读(258) | 评论(0) | 转发(0) |