Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions 104_maximum_depth_of_binary_tree/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 104. Maximum Depth of Binary Tree

https://leetcode.com/problems/maximum-depth-of-binary-tree/

## Comments

### step1

* まあ再帰で書こうかな、と思って 4:00 で AC
* `root` みたいな引数の関数を使うとなんか認知不可が高い気がする (`root` は木全体の根であって、再帰それぞれの根であるという感覚がないからな気がする)

### step2

* 引数名を `node` (`root` ではなく) にしたかったので、`GetDepth` のような private 関数を使おうかと思ったが、結局 depth って定義上はより深い方を返す (そうでないなら、右と左の pair を返すとかはできるけど) ということになり、そうすると `maxDepth` と全く同じ機能になるので分ける必要もない気がした。
* 一方でまあ深さを追加の引数として取って再帰するなら別の関数にする意味はある
* Arai60 で解いている
* https://github.com/ryosuketc/leetcode_arai60/pull/21/files
* 再帰のスタックオーバーフローとかを気にするなら、上記の通り iterative な解き方もあるかもしれない。上記は Python で書いたが、C++ なら `step2.Solution` みたいな感じかな。

### step3

* 省略
20 changes: 20 additions & 0 deletions 104_maximum_depth_of_binary_tree/step1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Definition for a binary tree node.
* 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 maxDepth(TreeNode* root) {
if (!root) {
return 0;
}
return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
33 changes: 33 additions & 0 deletions 104_maximum_depth_of_binary_tree/step2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Definition for a binary tree node.
* 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) {}
* };
*/

#include <stack>

class Solution {
public:
int maxDepth(TreeNode* root) {
std::stack<std::pair<TreeNode*, int>> node_and_depth;
node_and_depth.push(std::make_pair(root, 1));
int max_depth = 0;
while (!node_and_depth.empty()) {
auto [node, depth] = node_and_depth.top();
node_and_depth.pop();
if (!node) {
continue;
}
max_depth = std::max(max_depth, depth);
node_and_depth.push(std::make_pair(node->left, depth + 1));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自分ならここで if (node->left) し、無駄な push() と pop() を省くのですが、趣味の範囲だと思います。

node_and_depth.push(std::make_pair(node->right, depth + 1));
}
return max_depth;
}
};
Empty file.