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.
DFS
/**
* 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 minD(TreeNode *root,int depth){
if(root->left==NULL && root->right == NULL) return depth;
else if(root->left!=NULL && root->right == NULL) return minD(root->left,depth+1);
else if(root->left==NULL && root->right != NULL) return minD(root->right,depth+1);
else return min(minD(root->left,depth+1),minD(root->right,depth+1));
}
int minDepth(TreeNode *root) {
if(root == NULL) return 0;
return minD(root,1);
}
};