Skip to content

104. Maximum Depth of Binary Tree#20

Open
n6o wants to merge 1 commit intomainfrom
maximum-depth-of-binary-tree
Open

104. Maximum Depth of Binary Tree#20
n6o wants to merge 1 commit intomainfrom
maximum-depth-of-binary-tree

Conversation

@n6o
Copy link
Owner

@n6o n6o commented Feb 21, 2026

今回の問題

Maximum Depth of Binary Tree - LeetCode

使用言語

Go

次に解く問題

Minimum Depth of Binary Tree - LeetCode

Comment on lines +90 to +91
// GC対象にするため参照を外す
nodesToVisit[topIndex].node = nil
Copy link

Choose a reason for hiding this comment

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

こういう小技もあるのですね。勉強になります。
ちなみに、ここで参照を外さなくても、この関数を抜けたらGCは走りますよね…?

Copy link

Choose a reason for hiding this comment

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

これよく知らなかったのですが、ここの SliceTricks で推奨されていました。
https://go.dev/wiki/SliceTricks

NOTE If the type of the element is a pointer or a struct with pointer fields, which need to be garbage collected, the above implementations of Cut and Delete have a potential memory leak problem: some elements with values are still referenced by slice a’s underlying array, just not “visible” in the slice. Because the “deleted” value is referenced in the underlying array, the deleted value is still “reachable” during GC, even though the value cannot be referenced by your code. If the underlying array is long-lived, this represents a leak. The following code can fix this problem:

Copy link

Choose a reason for hiding this comment

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

おっしゃるとおりで、この関数抜けたら問題なく走るはずなので、状況によっては使ってもいいということかと思います。

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。

はい、 maxDepth から戻ったら nodesToVisit が参照されなくなるためGC対象となると思います。
手癖で書いていた側面もあるので、必要かどうか考えた上で nil 代入するかどうか考えるようにします。
生存期間が長くない、そもそもサイズ的に問題にならないなどの場合はなくてもいいと思いました。
(実務ではガイドラインに従います)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants