543. Diameter of Binary Tree - #71
Open
naoto-iwase wants to merge 2 commits into
Open
Conversation
nodchip
reviewed
Nov 29, 2025
| result = [] | ||
| stack = [(root, [], [], result)] | ||
| while stack: | ||
| node, left_output, right_output, output = stack[-1] |
There was a problem hiding this comment.
- 行きがけは left_output と right_output は空
- output が親ノードの left_output または right_output を指す
- 帰りがけに left_output と right_output が非空になっている
ということですね。普段あまり目にしない書き方だったため、読むのにやや時間がかかりました。
チームの平均的なソフトウェアエンジニアが現実的な時間で読めるのであれば、この書き方でも良いと思います。そうでない場合は、再帰で書いたほうが良いかもしれません。
Owner
Author
There was a problem hiding this comment.
ありがとうございます。ご理解の通りです。
リストの空/非空を「仕事完了フラグ」として兼用しているのが分かりにくさの原因だと思います。以下のようにdataclassで明示的にすれば多少改善しそうですが、それでもrecursiveの方が素直ですね。今回は練習としてiterativeで書いてみました。
from dataclasses import dataclass
@dataclass
class Job:
done: bool = False
diameter: Optional[int] = None
depth: Optional[int] = None
result = Job()
...
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
543. Diameter of Binary Tree
Next: 57. Insert Interval