Leetcode | Minimum/Maximum Depth of Binary Tree

时间:2021-10-30 06:11:35

Minimum Depth of Binary Tree

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.

BFS碰到一个叶子结点就可以了。

 class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL) return NULL; queue<TreeNode*> q;
q.push(root);
q.push(NULL);
int h = ;
while (q.size() > 1) {
TreeNode* p = q.front();
q.pop(); if (p == NULL) { h++; q.push(NULL); continue;}
if (p->left == NULL && p->right == NULL) break;
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
return h;
} };

这里用个NULL指针作哨兵,作为层的结束标志。所有遍历完时,q.size() == 1(q里面只有NULL一个点)。 不过这里因为只要到达叶子结点就会退出,所以不存在死循环的问题。

第三次,bugfree一遍通过。

 class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL) return ;
vector<vector<TreeNode*> > layers();
int cur = , next = , layer = ;
layers[cur].push_back(root);
while (!layers[cur].empty()) {
layers[next].clear();
for (auto node: layers[cur]) {
if (node->left == NULL && node->right == NULL) return layer;
if (node->left) layers[next].push_back(node->left);
if (node->right) layers[next].push_back(node->right);
}
cur = !cur, next = !next;
layer++;
}
return layer;
}
};

Maximum Depth of Binary Tree

同样是用bfs好记录层数,然后bfs结束返回值就行了。

 class Solution {
public:
int maxDepth(TreeNode *root) {
if (root == NULL) return ;
vector<vector<TreeNode*> > layers();
int cur = , next = , layer = ;
layers[cur].push_back(root);
while (!layers[cur].empty()) {
layers[next].clear();
for (auto node: layers[cur]) {
if (node->left) layers[next].push_back(node->left);
if (node->right) layers[next].push_back(node->right);
}
cur = !cur, next = !next;
layer++;
}
return layer;
}
};