Skip to content

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

Open
TakayaShirai 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#29
TakayaShirai wants to merge 1 commit intomainfrom
105_construct_binary_tree_from_preorder_and_inorder_traversal

Conversation

@TakayaShirai
Copy link
Copy Markdown
Owner

@TakayaShirai TakayaShirai self-assigned this Feb 21, 2026
Comment on lines +92 to +102
int pickInorderRootIndex(List<int> inorder, int rootValue) {
var rootIndex = 0;

for (var i = 0; i < inorder.length; i++) {
if (inorder[i] == rootValue) {
return i;
}
}

throw Exception('inorder does not have the given rootValue.');
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここは list.indexOf() を使うとどうでしょうか。
https://api.dart.dev/dart-core/List/indexOf.html

);

root.left = leftTree;
root.right = rightTree;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Dartに詳しくないのですが,以下のようにかけるのならそちらの方がシンプルだと感じました.root.leftという文字列,leftTreeという文字列から得られる情報はほとんど同じなので.

    root.left = buildTree(
      preorder.sublist(1, leftNodesCount + 1),
      inorder.sublist(0, rootIndex),
    );
    root.right = buildTree(
      preorder.sublist(leftNodesCount + 1),
      inorder.sublist(rootIndex + 1),
    );

Comment on lines +63 to +68
for (var i = 0; i < inorder.length; i++) {
if (inorder[i] == rootValue) {
rootIndex = i;
break;
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

indexOf()で良いと思いました.

class Solution {
TreeNode? buildTree(List<int> preorder, List<int> inorder) {
int pickInorderRootIndex(List<int> inorder, int rootValue) {
var rootIndex = 0;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こちらの変数はこの後参照されないですね.

@5ky7
Copy link
Copy Markdown

5ky7 commented Feb 25, 2026

全体的に読みやすいです.

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