diff --git a/tree-bst/111.md b/tree-bst/111.md index e69de29..0af57b0 100644 --- a/tree-bst/111.md +++ b/tree-bst/111.md @@ -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; + } + + return Math.min(left, right) + 1; + } +} +``` \ No newline at end of file