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<algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode * left;
TreeNode * right;
TreeNode(int x):val(x),left(NULL),right(NULL){ };
};
class Solution{
public:
int minDepth(TreeNode * root){
if(root==NULL) return 0;
if(root->left==NULL && root->right==NULL)
return 1;
return min(1+minDepth(root->left),1+minDepth(root->right));
}
};
int main() {
TreeNode a(5);
TreeNode b(4);
TreeNode c(8);
TreeNode d(11);
TreeNode e(13);
TreeNode f(4);
TreeNode g(7);
TreeNode h(2);
TreeNode i(1);
a.left=&b;a.right=&c;
b.left=&d;b.right=NULL;
c.left=&e;c.right=&f;
d.left=&g;d.right=&h;
e.left=NULL;e.right=NULL;
f.left=NULL;f.right=&i;
g.left=NULL;g.right=NULL;
h.left=NULL;h.right=NULL;
i.left=NULL;i.right=NULL;
Solution sol;
int result=sol.minDepth(&a);
cout<< result<<endl;
}