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.
» Solve this problem
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int depth;
void traversal(TreeNode *root, int d) {
if (root->left == NULL && root->right == NULL) {
depth = d < depth || depth == 0 ? d : depth;
}
else {
if (root->left != NULL) {
traversal(root->left, d + 1);
}
if (root->right != NULL) {
traversal(root->right, d + 1);
}
}
}
public:
int minDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
depth = 0;
if (root != NULL) {
traversal(root, 1);
}
return depth;
}
};