Skip to content

105.construct binary tree from preorder and inorder traversal#28

Open
tom4649 wants to merge 2 commits intomainfrom
105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal
Open

105.construct binary tree from preorder and inorder traversal#28
tom4649 wants to merge 2 commits intomainfrom
105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal

Conversation

@tom4649
Copy link
Copy Markdown
Owner

@tom4649 tom4649 commented Mar 26, 2026

node.left = gather_descendants(node_position)
stack.append(node)

return gather_descendants(-(10**30))
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この数字がどうやって決まっているのかわかりづらいので、Python にするのだったら float("-inf") とかの方が意図が伝わりやすいかもしれません。

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.

ご指摘の通りですね、ありがとうございます

inorder_val_to_idx[val] = i

def buildTree_w_index(
pre_left: int, in_left: int, num_children: int
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 num_children == 1:
return root
idx_root_inorder = inorder_val_to_idx[root.val]
num_left_children = idx_root_inorder - in_left
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

好みの範疇ですが、numよりはcountの方が個数ということを読み取りやすいと思いました。

for i, val in enumerate(inorder):
inorder_val_to_idx[val] = i

def buildTree_w_index(
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

メソッド名のwが何かを読み取れなかったので、略ではなく単語を使うことをお勧めします。

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.

withの略でしたが、わかりづらいのかもしれませんね。省略せずに書こうと思います。

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