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.
求最小深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int depth = 1e8;
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
DFS(root);
return depth;
}
int d = 0;
void DFS(TreeNode* root) {
d++;
if(root->left == NULL && root->right == NULL)
{
if(d < depth)
depth = d;
return;
}
if(root->left)
{
DFS(root->left);
d--;
}
if(root->right)
{
DFS(root->right);
d--;
}
}
};