-
Notifications
You must be signed in to change notification settings - Fork 0
111. Minimum Depth of Binary Tree #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hroc135
wants to merge
2
commits into
main
Choose a base branch
from
111MinimumDepthOfBinaryTree
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| ```Go | ||
| // Definition for a binary tree node. | ||
| type TreeNode struct { | ||
| Val int | ||
| Left *TreeNode | ||
| Right *TreeNode | ||
| } | ||
| ``` | ||
|
|
||
| ### Step 1 | ||
| - 最初は再帰で解けるかなと思ったが、つまづいたので、BFSでやることに | ||
| - 最短距離を探す問題なのでBFSの方が自然な発想 | ||
| - 最近ループ不変条件を気にするようになった | ||
| - 外側のforループでは、常に`nodesInCurrentLevel`に現在の`level`のnilでないノードが全て格納されている | ||
| - 初めてループ不変条件という概念を知ったときは「実際は誰も意識してなさそうだな」と思ったが、意外と頭の整理に使える | ||
| - 時間計算量:O(n) | ||
| - 空間計算量:O(log n) (二分木の同じ階層のノードは高々log n個なので) | ||
|
|
||
| ```Go | ||
| func minDepth(root *TreeNode) int { | ||
| if root == nil { | ||
| return 0 | ||
| } | ||
|
|
||
| level := 1 | ||
| nodesInCurrentLevel := []*TreeNode{root} | ||
| for { | ||
| nodesInNextLevel := []*TreeNode{} | ||
| for _, node := range nodesInCurrentLevel { | ||
| if node.Left == nil && node.Right == nil { | ||
| return level | ||
| } | ||
| if node.Left != nil { | ||
| nodesInNextLevel = append(nodesInNextLevel, node.Left) | ||
| } | ||
| if node.Right != nil { | ||
| nodesInNextLevel = append(nodesInNextLevel, node.Right) | ||
| } | ||
| } | ||
| level++ | ||
| nodesInCurrentLevel = nodesInNextLevel | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ### Step 2 | ||
| #### 2a | ||
| - nilノードもキューに入れるBFS | ||
| - step1のようにnilノードはキューに入れない方が自然な発想だとは思う | ||
| - この解法だと冒頭の`if root == nil { return 0 }`を消すことができる | ||
|
|
||
| ```Go | ||
| func minDepth(root *TreeNode) int { | ||
| level := 1 | ||
| nodesInCurrentLevel := []*TreeNode{root} | ||
| for len(nodesInCurrentLevel) > 0 { | ||
| nodesInNextLevel := []*TreeNode{} | ||
| for _, node := range nodesInCurrentLevel { | ||
| if node == nil { | ||
| continue | ||
| } | ||
| if node.Left == nil && node.Right == nil { | ||
| return level | ||
| } | ||
| nodesInNextLevel = append(nodesInNextLevel, node.Left) | ||
| nodesInNextLevel = append(nodesInNextLevel, node.Right) | ||
| } | ||
| level++ | ||
| nodesInCurrentLevel = nodesInNextLevel | ||
| } | ||
| return 0 | ||
| } | ||
| ``` | ||
|
|
||
| #### 2b | ||
| - 再帰 | ||
| - 自分で試したときは躓いたが、以下を参考に実装 | ||
| - https://github.com/seal-azarashi/leetcode/pull/21/files#r1752890984 | ||
| - https://github.com/hayashi-ay/leetcode/pull/26/files#diff-c2ef246709da963a01dc6a50ecb5b5ce1169312bb960fb96731d87c76e1aa8a4R33 | ||
| - ただし、Goでは再帰はループに直す傾向がある | ||
| - スタックサイズ見積もり | ||
| - 1フレームの大きさ = 引数8 + 返り値8 + ローカル変数(8*3) + ベースポインタ8 + 戻りアドレス8 = 56B | ||
| - 56B * 10^5 = 5.6MB | ||
| - Goは64bitマシンならスタックサイズ1GBまで耐えられるので大丈夫だろう | ||
| - 参考:https://github.com/rihib/leetcode/pull/41/files#diff-04b9326b75782ef947d7603c8de35ae07dcb272e8ce3949b7983749f0d26a001R20 | ||
|
|
||
| ```Go | ||
| func minDepth(root *TreeNode) int { | ||
| if root == nil { | ||
| return 0 | ||
| } | ||
| if root.Left == nil && root.Right == nil { | ||
| return 1 | ||
| } | ||
|
|
||
| depth := math.MaxInt | ||
| if root.Left != nil { | ||
| depth = min(depth, minDepth(root.Left)+1) | ||
| } | ||
| if root.Right != nil { | ||
| depth = min(depth, minDepth(root.Right)+1) | ||
| } | ||
|
|
||
| return depth | ||
| } | ||
| ``` | ||
|
|
||
| #### 2c | ||
| - levelを保持する構造体を使うBFS | ||
|
|
||
| ```Go | ||
| type nodeAndLevel struct { | ||
| node *TreeNode | ||
| level int | ||
| } | ||
|
|
||
| func minDepth(root *TreeNode) int { | ||
| if root == nil { | ||
| return 0 | ||
| } | ||
|
|
||
| queue := []nodeAndLevel{{node: root, level: 1}} | ||
| for len(queue) > 0 { | ||
| first := queue[0] | ||
| queue = queue[1:] | ||
|
|
||
| if first.node.Left == nil && first.node.Right == nil { | ||
| return first.level | ||
| } | ||
| if first.node.Left != nil { | ||
| queue = append(queue, nodeAndLevel{node: first.node.Left, level: first.level + 1}) | ||
| } | ||
| if first.node.Right != nil { | ||
| queue = append(queue, nodeAndLevel{node: first.node.Right, level: first.level + 1}) | ||
| } | ||
| } | ||
|
|
||
| log.Fatal("minDepth terminated with an unknown reason") | ||
| panic("unreachable") | ||
| } | ||
| ``` | ||
|
|
||
| #### 2d | ||
| - BFS | ||
| - step1で`nodesInNextLevel := []*TreeNode{}`としていた部分を、二分木の性質を考慮してキャパシティを上の階層のノード数の2倍に設定`nodesInNextLevel := make([]*TreeNode, 0, len(nodesInCurrentLevel)*2)` | ||
| - キャパシティを設定することにより、スライスがキャパシティオーバーでリロケートされるのを防ぐことができ、特に綺麗な形をした二分木に対して効果を発揮できる | ||
| - 実験:step1のコードとローカルで実行時間の差を計測 | ||
| - 1. 深さ17、ノード数2^17の綺麗な二分木(常に子が2ついる) | ||
| - 見積もり実行時間:2^17 / 10e8 ≒ 10e5 / 10e8 = 10e-3 = 1ms | ||
| - step1: 4.3ms | ||
| - 2d: 1.6ms | ||
| - 2. 深さ10e5、ノード数10e5の直線 | ||
| - step1: 4ms | ||
| - 2d: 5ms | ||
| - 予想通り、1のケースで効果を発揮してくれている | ||
|
|
||
| ```Go | ||
| func minDepth(root *TreeNode) int { | ||
| if root == nil { | ||
| return 0 | ||
| } | ||
|
|
||
| level := 1 | ||
| nodesInCurrentLevel := []*TreeNode{root} | ||
| for { | ||
| nodesInNextLevel := make([]*TreeNode, 0, len(nodesInCurrentLevel)*2) | ||
| for _, node := range nodesInCurrentLevel { | ||
| if node.Left == nil && node.Right == nil { | ||
| return level | ||
| } | ||
| if node.Left != nil { | ||
| nodesInNextLevel = append(nodesInNextLevel, node.Left) | ||
| } | ||
| if node.Right != nil { | ||
| nodesInNextLevel = append(nodesInNextLevel, node.Right) | ||
| } | ||
| } | ||
|
|
||
| level++ | ||
| nodesInCurrentLevel = nodesInNextLevel | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ### Step 3 | ||
| - BFS(階層ごとにスライスを作る方法、スライスのキャパシティを指定) | ||
|
|
||
| ```Go | ||
| func minDepth(root *TreeNode) int { | ||
| if root == nil { | ||
| return 0 | ||
| } | ||
|
|
||
| level := 1 | ||
| currentLevelNodes := []*TreeNode{root} | ||
| for { | ||
| nextLevelNodes := make([]*TreeNode, 0, len(currentLevelNodes)*2) | ||
| for _, node := range currentLevelNodes { | ||
| if node.Left == nil && node.Right == nil { | ||
| return level | ||
| } | ||
| if node.Left != nil { | ||
| nextLevelNodes = append(nextLevelNodes, node.Left) | ||
| } | ||
| if node.Right != nil { | ||
| nextLevelNodes = append(nextLevelNodes, node.Right) | ||
| } | ||
| } | ||
| level++ | ||
| currentLevelNodes = nextLevelNodes | ||
| } | ||
| } | ||
| ``` | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
log_10 2 ~ 0.301 を覚えておくと速いです。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.