Skip to content
Open
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
50 changes: 50 additions & 0 deletions tree-bst/111.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
- [111. Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/description/)
- 方針
- DFS
- 再帰関数
- example. 2 で出ているような一直線タイプは前回の問題だと厳しいので、枝ノード(left があるのか?right があるのか?)の扱いに気をつけないといけない, 存在しないパスを最短と判断してしまうため
- 時間計算量: `O(N)`, 空間計算量: `O(N)`
- Stack
- 無理やりやれるけどやらない、前回の問題で[似たようなこと](https://github.com/hiroki-horiguchi-dev/leetcode/pull/21)をしているが、あまり勉強になるとは思わなかった
- BFS
- Queue
- 同様にやらない

### 再帰関数
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}

int left = minDepth(root.left);
int right = minDepth(root.right);

if (root.left != null && root.right == null) {
return left + 1;
}

if (root.left == null && root.right != null) {
return right + 1;
}
Comment on lines +36 to +45

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 (root.left == null) {
    return minDepth(root.right) + 1;
}
if (root.right == null) {
    return minDepth(root.left) + 1;
}

return Math.min(minDepth(root.left), minDepth(root.right)) + 1;

@hiroki-horiguchi-dev hiroki-horiguchi-dev Jun 7, 2026

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

コメントの返信が遅くなりすみません。
ありがとうございます、おっしゃる通りですね。
方針部分で書いたように、leaf Node と brach node を分けて書くことを意識した結果、コメントいただいたコードになりました。

が、コメントいただいたコードの方が冗長な分岐と変数がなく、スッキリしていてわかりやすいですね。
「自然言語で方針を説明できる --> 手作業をそのまま起こしたようなコードを書く --> 冗長な箇所を削る」を含めて短時間でできるように意識していきたいと思います。


return Math.min(left, right) + 1;
}
}
```