Skip to content

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

Open
xbam326 wants to merge 2 commits into
mainfrom
105
Open

105.construct binary tree from preorder and inorder traversal#31
xbam326 wants to merge 2 commits into
mainfrom
105

Conversation

@xbam326
Copy link
Copy Markdown
Owner

@xbam326 xbam326 commented Mar 28, 2026

root_index_at_inorder = inorder.index(root_val)

has_left = root_index_at_inorder != 0
if has_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.

最初に preorder/inorder が空かどうかをチェックすることで、少しシンプルにできそうです。

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:
            return None

        root_val = preorder[0]
        root = TreeNode(preorder[0])
        root_index_at_inorder = inorder.index(root_val)

        root.left = self.buildTree(
            preorder[1 : root_index_at_inorder + 1],
            inorder[:root_index_at_inorder],
        )

        root.right = self.buildTree(
            preorder[root_index_at_inorder + 1 :],
            inorder[root_index_at_inorder + 1 :],
        )

        return root

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.

2 participants