Conversation
| } | ||
|
|
||
| private: | ||
| int preorder_index = 0; |
There was a problem hiding this comment.
Solutionインスタンスが作られ、そのインスタンスでbuildTree()が複数回呼ばれた場合を考えるとpreorder_indexが初期化されずバグる気がします。そこを考慮するかという問題はあるかもしれないですが。
There was a problem hiding this comment.
たとえば、HTML Parser だったら、HTML 一つにつきインスタンス一つという設計も自然でしょう。呼ぶ側の気持ちになってどう実装するかを考えるということかと思います。
通常、プログラムというのは、誰かに使って欲しいと思って書かれていて、つまり、それがエンジニアリングをしているということです。ライブラリーの場合は、それは呼ぶ相手のためにエンジニアリングをしているはずです。
| class Solution { | ||
| public: | ||
| TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { | ||
| if (!inorder.empty()) { |
There was a problem hiding this comment.
if (inorder.empty()) {
return nullptr;
}
...の形の方がコードを読みながら考えることが減って読みやすいかなと思います
There was a problem hiding this comment.
@fhiyo
hash_map_step2にて実装しました。
ネストが浅くなる分こちらの方が読みやすいですね。
改めてみてみると最下部にreturn nullptrがあるのは読みづらいですね。
| TreeNode* BuildTreeHelper(const vector<int>& preorder, int preorder_start, int preorder_end, | ||
| const vector<int>& inorder, int inorder_start, int inorder_end) { |
There was a problem hiding this comment.
preorder_end - preorder_start == inorder_end - inorder_start という制約があるので、これをtree_sizeとかの名前にして、preorder, inorder, preorder_start, inorder_start, tree_size の引数を渡す方が自然な気がしました。
There was a problem hiding this comment.
レビューありがとうございます。
step6に実装してみました。少しスッキリしました。
| int value = preorder[preorder_start]; | ||
| TreeNode* node = new TreeNode(value); | ||
|
|
||
| int position = FindSeparatingPosition(inorder, inorder_start, inorder_end, value); |
There was a problem hiding this comment.
positionという変数名が曖昧かなと思いました。
これはinorderにおける根を表すindexだと思うので、inorder_root_indexとかでしょうか
あと、indexをいじるのは認知不可が上がるので、inorder, preorderそれぞれのsliceを引き回すようにすると読みやすくなると思いました
There was a problem hiding this comment.
@Yoshiki-Iwasa
レビューありがとうございます。inorder_root_index使わせていただきました。
indexをいじるのは認知不可が上がるので、inorder, preorderそれぞれのsliceを引き回すようにすると読みやすくなると思いました
今回複数パターン書いてみましたが、indexを触るverは理解するのが辛かったです。
| forループでindexを見つけてからiteratorに変換していたがfind関数が存在していた | ||
|
|
||
|
|
||
| ## 他の解法 |
There was a problem hiding this comment.
preorderとinorderを使って順に木を構築する方法もあります。
問題へのリンク
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
問題文(プレミアムの場合)
備考
次に解く問題の予告
arai60ではないですが以前、赤黒木を実装している際に知識の補強として教えていただいた問題です。
https://leetcode.com/problems/binary-search-tree-iterator/description/
フォルダ構成
LeetCodeの問題ごとにフォルダを作成します。
フォルダ内は、step1.cpp、step2.cpp、step3.cpp
hash_map.cppとstep4.cpp(step3の非破壊的変更ver)とmemo.mdとなります。
memo.md内に各ステップで感じたことを追記します。