From 3ab34c698adf86eadd982c2e2d76470b4dfa51b8 Mon Sep 17 00:00:00 2001 From: Yu Nakamura Date: Mon, 13 Apr 2026 14:44:55 +0900 Subject: [PATCH] add files --- 0111-minimum-depth-of-binary-tree/memo.md | 11 +++++++++++ 0111-minimum-depth-of-binary-tree/step1.cpp | 21 +++++++++++++++++++++ 0111-minimum-depth-of-binary-tree/step2.cpp | 21 +++++++++++++++++++++ 0111-minimum-depth-of-binary-tree/step3.cpp | 21 +++++++++++++++++++++ 4 files changed, 74 insertions(+) create mode 100644 0111-minimum-depth-of-binary-tree/memo.md create mode 100644 0111-minimum-depth-of-binary-tree/step1.cpp create mode 100644 0111-minimum-depth-of-binary-tree/step2.cpp create mode 100644 0111-minimum-depth-of-binary-tree/step3.cpp diff --git a/0111-minimum-depth-of-binary-tree/memo.md b/0111-minimum-depth-of-binary-tree/memo.md new file mode 100644 index 0000000..286f2e5 --- /dev/null +++ b/0111-minimum-depth-of-binary-tree/memo.md @@ -0,0 +1,11 @@ +### step1 + +maximum depth of binary treeを参考に、左や右のnodeがない場合の処理だけ書いたら解けた。 + +### step2 + +変更点なし。 + +### step3 + +3回通すまで書き直し。 diff --git a/0111-minimum-depth-of-binary-tree/step1.cpp b/0111-minimum-depth-of-binary-tree/step1.cpp new file mode 100644 index 0000000..42ac17b --- /dev/null +++ b/0111-minimum-depth-of-binary-tree/step1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + + int leftDepth = minDepth(root->left); + int rightDepth = minDepth(root->right); + + if (leftDepth == 0) { + return rightDepth + 1; + } + + if (rightDepth == 0) { + return leftDepth + 1; + } + + return min(leftDepth, rightDepth) + 1; + } +}; diff --git a/0111-minimum-depth-of-binary-tree/step2.cpp b/0111-minimum-depth-of-binary-tree/step2.cpp new file mode 100644 index 0000000..42ac17b --- /dev/null +++ b/0111-minimum-depth-of-binary-tree/step2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + + int leftDepth = minDepth(root->left); + int rightDepth = minDepth(root->right); + + if (leftDepth == 0) { + return rightDepth + 1; + } + + if (rightDepth == 0) { + return leftDepth + 1; + } + + return min(leftDepth, rightDepth) + 1; + } +}; diff --git a/0111-minimum-depth-of-binary-tree/step3.cpp b/0111-minimum-depth-of-binary-tree/step3.cpp new file mode 100644 index 0000000..42ac17b --- /dev/null +++ b/0111-minimum-depth-of-binary-tree/step3.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + + int leftDepth = minDepth(root->left); + int rightDepth = minDepth(root->right); + + if (leftDepth == 0) { + return rightDepth + 1; + } + + if (rightDepth == 0) { + return leftDepth + 1; + } + + return min(leftDepth, rightDepth) + 1; + } +};