Skip to content

105. Construct Binary Tree from Preorder and Inorder Traversal#28

Open
5103246 wants to merge 1 commit intomainfrom
105-construct-binary-tree-from-preorder-and-inorder-traversal
Open

105. Construct Binary Tree from Preorder and Inorder Traversal#28
5103246 wants to merge 1 commit intomainfrom
105-construct-binary-tree-from-preorder-and-inorder-traversal

Conversation

@5103246
Copy link
Copy Markdown
Owner

@5103246 5103246 commented Oct 25, 2025

int preorder_index = 0;
return BuildTreeHelper(preorder,value_to_inorder_index, 0, inorder.size() - 1, preorder_index);
}
private:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

自分なら private: の前に空行を入れ、コードの塊を視覚的に分かりやすし、読み手にとって読みやすくします。人によって判断が分かれるかもしれません。
Google の C++ Style ガイドには入れ過ぎないように、読み手に取ってコードの構造が分かりやすいように入れましょうと書かれているようです。

参考までにスタイルガイドへのリンクを貼ります。

https://google.github.io/styleguide/cppguide.html#Vertical_Whitespace

Use vertical whitespace sparingly; unnecessary blank lines make it harder to see overall code structure. Use blank lines only where they aid the reader in understanding the structure.

上記のスタイルガイドは唯一絶対のルールではなく、複数あるスタイルガイドの一つに過ぎないということを念頭に置くことをお勧めします。また、所属するチームにより何が良いとされているかは変わります。自分の中で良い書き方の基準を持ちつつ、チームの平均的な書き方で書くことをお勧めいたします。

const map<int, int>& value_to_inorder_index,
int left, int right,
int& preorder_index) {
if (!(preorder_index < preorder.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.

ここは ! を使うことによって読みやすくなる情報がないため、単に

if (preorder_index => preorder.size()) {

もしくは

if (preorder.size() <= preorder_index) {

が良いと思います。

1. valueとそれがinorderのどこにあるかをmapで対応付ける(value : inorder_index)
2. DFS関数を呼ぶ。渡すものは、preorder、区間[left, right]、map, preorderのindex
3. preorderのindexがリストのサイズを超えたらnullptrを返す。
4. preorderの値に対応するinorder_indexが[left,right]内になかったらnullptr
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この条件を満たすことがないように思いました。

int left_tree_size = inorder_index - inorder_start;
int right_tree_size = size - left_tree_size - 1;
TreeNode* node = new TreeNode(value);
++preorder_start;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここでインクリメントせずに引数に渡すときに+1するのがよい気がしました。

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.

3 participants