Create 105. Construct Binary Tree from Preorder and Inorder Traversal.md#32
Conversation
| TreeNode* BuildTreeHelper(vector<int>& preorder, int left, int right, | ||
| const std::map<int, int>& value_to_inorder_index, | ||
| int& preorder_index) { | ||
| if (preorder_index >= preorder.size()) { |
There was a problem hiding this comment.
細かいですが、37行目の考え方と統一して、
if (!(preorder_index < preorder.size()))としたくなりました。
There was a problem hiding this comment.
ありがとうござます。おっしゃる通り一貫した記載にするべきでした
| if (preorder_index == preorder.size()) { | ||
| break; | ||
| } | ||
| // DFS順に探索するため、stackにright→leftの順番でstackに積む |
There was a problem hiding this comment.
ありがとうございます。in-order順をDFS順と誤って覚えてしまっていました。
| nodes_right_unfixed); | ||
| nodes_right_unfixed.push(node); | ||
| } | ||
| return gather_descendants(-1, value_to_preorder_index, nodes_right_unfixed); |
There was a problem hiding this comment.
-1の意図を理解するのに手間取りました。
static const int ROOT_PARENT_POSITION = -1;とでも置いた方が、任意のノードよりも前にあることが伝わる気がします。
There was a problem hiding this comment.
個人的には定数に置くよりもコメントで意図を書くほうがいいと思います。全部追い出すということですよね。
There was a problem hiding this comment.
コメントありがとうございます。いずれにしても、-1とだけ書いてもあまり伝わらないので、コメントか意味を持たせた定数で読み手の理解をスムーズにできるようにします
| return gather_descendants(-1, value_to_preorder_index, nodes_right_unfixed); | ||
| } | ||
| private: | ||
| TreeNode* gather_descendants(int node_position, |
There was a problem hiding this comment.
好みの問題だと思いますが、ここのnodeはparent_node等の命名をつけても良いかもしれません。
There was a problem hiding this comment.
ありがとうございます。
おっしゃる通り、parent以下にまだ右側が確定していないノードを纏めて繋げるという意味の関数ですので、parentをつけた方が意味がわかりやすいと思いました。
| nodes_right_unfixed); | ||
| nodes_right_unfixed.push(node); | ||
| } | ||
| return gather_descendants(-1, value_to_preorder_index, nodes_right_unfixed); |
There was a problem hiding this comment.
個人的には定数に置くよりもコメントで意図を書くほうがいいと思います。全部追い出すということですよね。
|
|
||
| ``` | ||
|
|
||
| - inorder順に走査して、preorderの制限を確認しながらnodeを埋めていく方法 https://github.com/tarinaihitori/leetcode/pull/29/files#r2044913447 |
There was a problem hiding this comment.
この解き方は、このあたりに触発されて書いたものなので、こういうこともできる話半分くらいでいいと思います。
kazukiii/leetcode#30 (comment)
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0
This Problem
Construct Binary Tree from Preorder and Inorder Traversal
Next Problem
Paint Fence