feat: 111_minimum_depth_of_binary_tree
This commit is contained in:
parent
7a5e03d227
commit
a41c9a4e18
44
111_minimum_depth_of_binary_tree/main.cpp
Normal file
44
111_minimum_depth_of_binary_tree/main.cpp
Normal file
@ -0,0 +1,44 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
struct TreeNode {
|
||||
int val;
|
||||
TreeNode *left;
|
||||
TreeNode *right;
|
||||
TreeNode() : val(0), left(nullptr), right(nullptr) {}
|
||||
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
||||
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
|
||||
};
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int minDepth(TreeNode *root) {
|
||||
queue<TreeNode *> bfsQueue;
|
||||
unordered_map<TreeNode *, int> depthTable;
|
||||
|
||||
if (root) {
|
||||
depthTable[root] = 1;
|
||||
bfsQueue.emplace(root);
|
||||
}
|
||||
|
||||
while (!bfsQueue.empty()) {
|
||||
TreeNode *currentNode = bfsQueue.front();
|
||||
bfsQueue.pop();
|
||||
|
||||
if (!currentNode->left && !currentNode->right) {
|
||||
return depthTable[currentNode];
|
||||
}
|
||||
|
||||
if (currentNode->left) {
|
||||
depthTable[currentNode->left] = depthTable[currentNode] + 1;
|
||||
bfsQueue.emplace(currentNode->left);
|
||||
}
|
||||
if (currentNode->right) {
|
||||
depthTable[currentNode->right] = depthTable[currentNode] + 1;
|
||||
bfsQueue.emplace(currentNode->right);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user