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.
就是对树进行遍历,每次深度+1,当左右节点都为空的时候表示到达了叶节点,比较如果比当前的min小,则记录。
/**
* 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:
void dfs(TreeNode* root, int &min, int dep)
{
if (root == NULL) return;
if (root->left == NULL && root->right == NULL)
{
if (min > dep) min = dep;
return;
}
dfs(root->left, min, dep + 1);
dfs(root->right, min, dep + 1);
}
int minDepth(TreeNode* root) {
if (!root) return 0;
int min = 9999;
dfs(root, min, 1);
return min;
}
};