-
Notifications
You must be signed in to change notification settings - Fork 0
105. Construct Binary Tree from Preorder and Inorder Traversal #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
変数の命名も含め読みやすいコードだと思いました。 |
root_index_in_inorder = inorder.index(root_value) | ||
num_of_left_node = root_index_in_inorder | ||
root = TreeNode(root_value) | ||
root.left = self.buildTree(preorder[1:1 + num_of_left_node], inorder[:root_index_in_inorder]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
細かい点となりますが、「変数 + 1」と「1 + 変数」は、「変数 + 1」 に統一したほうが読みやすいかなと思いました。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
「インデックスの位置 + ずらす個数」という役割で順番を決めていましたが、指摘された内容も確かにと思いました。
「1 + num_of_left_node」は、rootの位置の隣(1)からnum_of_left_node分
「inorder[root_index_in_inorder + 1:]」はroot_index_in_inorderの位置から1つ分
|
||
def build_tree_in_preorder(left, right): | ||
nonlocal root_index | ||
if left >= right: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if left == right:
で十分ではないでしょうか…?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
仰る通りですが、 if left == right
のみだとif left > right
のケースが考慮しなくて良いということを読み手が確認するひと手間が発生するかなと思いif left >= right
にしました。
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/