Likou 105. Construct binary trees from preorder and inorder traversal sequences

Topic source: 105. Constructing binary tree from preorder and inorder traversal sequence
Topic: Given two integer arrays preorder and inorder, where preorder is the preorder traversal of the binary tree, and inorder is the inorder traversal of the same tree, please construct the binary tree and return its root node.
insert image description here
insert image description here

Ideas: diagram
python code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if len(preorder) == 0:
            return None
        if len(preorder) == 1:
            return TreeNode(preorder[0])
        root = TreeNode(preorder[0])
        index = inorder.index(root.val)
        root.left = self.buildTree(preorder[1:index+1], inorder[:index])
        root.right = self.buildTree(preorder[index+1:], inorder[index+1:])

        return root

insert image description here

Reference link: [Leetcode][python]Construct binary tree from preorder and inorder traversal sequence/construct binary tree from inorder and postorder traversal sequence
Image source

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324354423&siteId=291194637