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.
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int mindepth = INT_MAX;
void finddepth(TreeNode* curnode, int depth)
{
if (curnode == NULL)
return;
if (!curnode->left&&!curnode->right){
mindepth = depth+1 < mindepth ? depth+1 : mindepth;
return;
}
finddepth(curnode->left, depth + 1);
finddepth(curnode->right, depth + 1);
}
int minDepth(TreeNode *root) {
if (root == NULL)
return 0;
finddepth(root, 0);
return mindepth;
}