diff --git a/111/step1.cpp b/111/step1.cpp new file mode 100644 index 0000000..de9619f --- /dev/null +++ b/111/step1.cpp @@ -0,0 +1,28 @@ +/* +Solve Time : 07:17 + +Time : O(V + E) +Space : O(V) + +root ~ leafまでの距離、という部分を読み違えて時間を多少ロスしたものの、特につまるところなく解けた。 +*/ +class Solution { +public: + int minDepth(TreeNode* root) { + queue> nodes_and_depths; + nodes_and_depths.emplace(root, 1); + while (!nodes_and_depths.empty()) { + auto [node, depth] = nodes_and_depths.front(); + nodes_and_depths.pop(); + if (!node) { + continue; + } + if (node->left == nullptr && node->right == nullptr) { + return depth; + } + nodes_and_depths.emplace(node->left, depth + 1); + nodes_and_depths.emplace(node->right, depth + 1); + } + return 0; + } +}; diff --git a/111/step2.cpp b/111/step2.cpp new file mode 100644 index 0000000..beb9559 --- /dev/null +++ b/111/step2.cpp @@ -0,0 +1,26 @@ +/* +Time : O(V + E) +Space : O(V) + +再帰,DFSで解いてみる。 +rootの処理をどうしても分岐で処理できなかったので最初のrootの面倒を見る関数と再帰処理をする関数とに分けた。 +*/ +class Solution { +public: + int minDepth(TreeNode* root) { + if (!root) { + return 0; + } + return minDepthRecursive(root); + } + private: + int minDepthRecursive(TreeNode* root) { + if (!root) { + return numeric_limits::max(); + } + if (root->left == nullptr && root->right == nullptr) { + return 1; + } + return min(minDepthRecursive(root->left), minDepthRecursive(root->right)) + 1; + } +}; diff --git a/111/step3.cpp b/111/step3.cpp new file mode 100644 index 0000000..08e242a --- /dev/null +++ b/111/step3.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int minDepth(TreeNode* root) { + queue> nodes_and_depths; + nodes_and_depths.emplace(root, 1); + while (!nodes_and_depths.empty()) { + auto [node, depth] = nodes_and_depths.front(); + nodes_and_depths.pop(); + if (!node) { + continue; + } + if (!(node->left || node->right)) { + return depth; + } + nodes_and_depths.emplace(node->left, depth + 1); + nodes_and_depths.emplace(node->right, depth + 1); + } + return 0; + } +};