105. Construct Binary Tree from Preorder and Inorder Traversal#31
105. Construct Binary Tree from Preorder and Inorder Traversal#31
Conversation
| ```py | ||
| class Solution: | ||
| def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: | ||
| def build(pre_start: int, in_start: int, size: int) -> Optional[TreeNode]: |
There was a problem hiding this comment.
preとinは'preorder'と'inorder'の略だと思いますが省略しない方が伝わりやすい気がしました。
There was a problem hiding this comment.
そうですね、ありがとうございます。あと伝えるという意味ではコメントに引数の説明を書く方針でも良かったかなとも思いました (何のstartなのかわからないので。あとdocstringにしてもいいかも)
# pre_start: starting index of the subtree in the preorder list
# in_start: starting index of the subtree in the inorder list
# size: number of nodes in the subtree
def build(pre_start: int, in_start: int, size: int) -> Optional[TreeNode]:
...| node = root | ||
| inorder_index = value_to_inorder_index[value] | ||
| while True: | ||
| assert inorder_index != value_to_inorder_index[node.val] |
There was a problem hiding this comment.
ここでアサーションが上手くいかなかったときにinorder_indexやnode.valを出力してあげてもよい気がしました。
| in_node_index = value_to_inorder_index[node.val] | ||
| left_tree_size = in_node_index - in_start | ||
| right_tree_size = size - left_tree_size - 1 | ||
| if left_tree_size: |
There was a problem hiding this comment.
このサイズチェックをせずに、stack に積んで、stack から出てきたところでチェックも一つですね。
| for i, value in enumerate(inorder): | ||
| value_to_inorder_index[value] = i | ||
| root = TreeNode(preorder[0]) | ||
| tree_info_stack = [(root, 0, 0, len(preorder))] # node, preorder_start, inorder_start, tree_size |
| ```py | ||
| class Solution: | ||
| def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: | ||
| if not preorder: |
There was a problem hiding this comment.
問題設定上 len(preorder) == len(inorder) のはずだから、というだけですね。そこでチェックしたりまたはassertとか入れてもいいんですが、細かくチェックしようとするとpreoderの値が全てinorderの中に入ってることとか、全部値がユニークになっていて重複がないこととかも気になってくるので、入力は事前条件を満たしていることを前提にしちゃいました。
(実務上このケースでどうすべきなのかは分からないですが...)
There was a problem hiding this comment.
問題の制約で1 <= preorder.length <= 3000があるので、一部の制約だけ前提にしているのかと単純な疑問で聞いてみました。
問題上なくても、空の入力をチェックするのは賛同します。
実務上は要件次第ではありますが、私は最初に空の入力チェックだけしてinorderのインデックスを探す時に見つからなかったら例外処理という形にすると思いました。
There was a problem hiding this comment.
あ、制約上は空配列来なかったですか。勘違いしていました...でもそうですね、空の入力チェックはそれでもやると思います。
たしかに、多分自分もできる範囲で例外処理仕込むかな、という気がしました。
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/