diff --git a/104/step1.cpp b/104/step1.cpp new file mode 100644 index 0000000..dba929b --- /dev/null +++ b/104/step1.cpp @@ -0,0 +1,19 @@ +/* +Solve Time : 2:56 + +Time : O(V + E) +Space : O(V) + +特に問題なく解いた、ひとまず一番シンプルにかける再帰を使用したが、queueやstackを使用したほうがよいはず。 +*/ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + const int left_depth = maxDepth(root->left); + const int right_depth = maxDepth(root->right); + return max(left_depth, right_depth) + 1; + } +}; diff --git a/104/step2_1.cpp b/104/step2_1.cpp new file mode 100644 index 0000000..f6257d8 --- /dev/null +++ b/104/step2_1.cpp @@ -0,0 +1,23 @@ +/* +Time : O(V + E) +Space : O(V) +*/ +class Solution { +public: + int maxDepth(TreeNode* root) { + stack> nodes_and_depths; + nodes_and_depths.emplace(root, 0); + int max_depth = 0; + while (!nodes_and_depths.empty()) { + auto [node, depth] = nodes_and_depths.top(); + nodes_and_depths.pop(); + if (node == nullptr) { + continue; + } + max_depth = max(max_depth, depth + 1); + nodes_and_depths.emplace(node->left, depth + 1); + nodes_and_depths.emplace(node->right, depth + 1); + } + return max_depth; + } +}; diff --git a/104/step3.cpp b/104/step3.cpp new file mode 100644 index 0000000..781f40e --- /dev/null +++ b/104/step3.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maxDepth(TreeNode* root) { + queue> nodes_and_depths; + nodes_and_depths.emplace(root, 0); + int max_depth = 0; + while (!nodes_and_depths.empty()) { + auto [node, depth] = nodes_and_depths.front(); + nodes_and_depths.pop(); + max_depth = depth; + if (!node) { + continue; + } + nodes_and_depths.emplace(node->left, depth + 1); + nodes_and_depths.emplace(node->right, depth + 1); + } + return max_depth; + } +};