递归做法:
用全局变量记录最小的深度,函数内的局部变量记录到达当前节点的深度
class Solution {
public:
int depth = 1e9;
int min(int a, int b) { return a < b ? a : b; }
void search(TreeNode* root, int count) {
if (root == nullptr)
return;
count++;
if (root->left == nullptr && root->right == nullptr)
depth = min(depth, count);
search(root->left, count);
search(root->right, count);
}
int minDepth(TreeNode* root) {
if (root == nullptr)
return 0;
search(root, 0);
return depth;
}
};
迭代法:
层序遍历到每一层时,如有叶子节点则返回当前层数
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> w;
if (root)
w.push(root);
int minDepth = 0;
while (!w.empty()) {
TreeNode* node;
int size = w.size();
minDepth++;
for (int i = 0; i < size; i++) {
node = w.front();
if (node->left == nullptr && node->right == nullptr)
return minDepth ;
if (node->left)
w.push(node->left);
if (node->right)
w.push(node->right);
w.pop();
}
}
return minDepth;
}
};