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 AllNode(TreeNode *node,int pathnum,int min)
{
pathnum = pathnum + 1;
if(node->left == NULL && node->right == NULL)
{
if (min == 1)
{
min = pathnum;
}
if (pathnum < min)
{
return pathnum;
}
else
return min;
}
if (node->left != NULL)
{
min = AllNode(node->left, pathnum, min);
}
if(node->right != NULL)
{
int x = AllNode(node->right,pathnum, min);
if (min == 1)
{
min = x;
}
else
min = min<x?min:x;
}
return min;
}
int minDepth(TreeNode *root)
{
if (root == NULL)
{
return 0;
}
else
return AllNode(root,0,1);
}
};