Skip to content

104. Maximum Depth of Binary Tree#20

Open
seal-azarashi wants to merge 3 commits intomainfrom
maximum-depth-of-binary-tree
Open

104. Maximum Depth of Binary Tree#20
seal-azarashi wants to merge 3 commits intomainfrom
maximum-depth-of-binary-tree

Conversation

@seal-azarashi
Copy link
Copy Markdown
Owner

@Yoshiki-Iwasa
Copy link
Copy Markdown

良さそうです

treeNodes.addLast(root);
int maxDepth = 0;
while (!treeNodes.isEmpty()) {
int levelNodeCountSnapshot = treeNodes.size();
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

単にnodeCountか変数に入れないでもtreeNodes.size();で数とわかるので良いかなと思いました。

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.

for 文開始時点ではそうなのですが、処理の中で要素数が増える場合に意図しない挙動 (レベルごとに for 文が終わらない) となってしまうので、開始時点の size を何らかの方法で残しておくのは必要だと認識してます。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これ、WordLadder と同じコメントですが、maxDepth と treeNodes と levelNodeCountSnapshot の関係がかなり密なので、ある瞬間に treeNodes に何が入っているかというのが、自然言語で表現すると複雑になるはずです。
「前から levelNodeCountSnapshot - i 個は maxDepth の深さのノードが入っていて、それより後ろは、maxDepth + 1 の深さのノードが入っている」ということですよね。これを読み解くヒントもあまりないです。

案としては、「maxDepth の深さのノードの入った配列」と「maxDepth + 1 の深さのノードの入った配列」に分けるか「ノードとその深さの組が入った Deque」などやり方はいろいろでしょう。

@Ryotaro25
Copy link
Copy Markdown

レビュー遅くなりました。全体的に綺麗なコードだと思いました。

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.

4 participants