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 <cstdio>
#include <cstring>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int run(TreeNode *root) {
if(root == NULL) {
return 0;
}
if(root->left == NULL && root->right == NULL) {
return 1;
}
else if(root->right != NULL && root->left == NULL) {
return 1 + run(root->right);
} else if(root->right == NULL && root->left != NULL) {
return 1 + run(root->left);
}
int leftDepth = run(root->left);
int rightDepth = run(root->right);
return 1 + min(leftDepth, rightDepth);
}
};
int main()
{
TreeNode *root = new TreeNode(1);
TreeNode *left = new TreeNode(2);
TreeNode *right = new TreeNode(3);
root->left = left;
root->right = right;
Solution *obj = new Solution();
int minDepth = obj->run(root);
cout << minDepth << endl;
return 0;
}