Skip to content

543. Diameter of Binary Tree - #71

Open
naoto-iwase wants to merge 2 commits into
mainfrom
0543-diameter-of-binary-tree
Open

543. Diameter of Binary Tree#71
naoto-iwase wants to merge 2 commits into
mainfrom
0543-diameter-of-binary-tree

Conversation

@naoto-iwase

Copy link
Copy Markdown
Owner

543. Diameter of Binary Tree


Next: 57. Insert Interval

result = []
stack = [(root, [], [], result)]
while stack:
node, left_output, right_output, output = stack[-1]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  • 行きがけは left_output と right_output は空
  • output が親ノードの left_output または right_output を指す
  • 帰りがけに left_output と right_output が非空になっている

ということですね。普段あまり目にしない書き方だったため、読むのにやや時間がかかりました。
チームの平均的なソフトウェアエンジニアが現実的な時間で読めるのであれば、この書き方でも良いと思います。そうでない場合は、再帰で書いたほうが良いかもしれません。

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.

ありがとうございます。ご理解の通りです。

リストの空/非空を「仕事完了フラグ」として兼用しているのが分かりにくさの原因だと思います。以下のようにdataclassで明示的にすれば多少改善しそうですが、それでもrecursiveの方が素直ですね。今回は練習としてiterativeで書いてみました。

from dataclasses import dataclass

@dataclass
class Job:
    done: bool = False
    diameter: Optional[int] = None
    depth: Optional[int] = None

result = Job()
...

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.

2 participants