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; + } +};