Record problem solution: Sword refers to Offer 07. Rebuild binary tree

Input the results of preorder traversal and inorder traversal of a binary tree, please build the binary tree and return its root node.

Assume that neither the input pre-order traversal nor the in-order traversal results contain duplicate numbers.

Example 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: preorder = [-1], inorder = [-1]
Output: [-1]

 Idea: It is necessary to understand the positional relationship between the root node of the binary tree and the left and right nodes in the pre-order traversal and post-order traversal.

Pre-order traversal: root left and right; in-order traversal: left root right. This reverses the construction of the binary tree.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder) == 0:
            return None
        root = TreeNode(preorder[0]) # 构建根节点
        idx = inorder.index(root.val) # 左子树的节点数目(标记所在根节点的下标,在中序遍历中,第一个到根节点的前一个的长度为二叉树左子树的长度)
        root.left = self.buildTree(preorder[1:idx+1] , inorder[0:idx]) 
        # 递归左子树,其中左子树部分的前序遍历的切片为第二个节点到左子树长度+1(左闭右开区间);中序遍历为,总的中序遍历切片的第一个节点到左子树长度处。
        root.right = self.buildTree(preorder[idx+1:] ,inorder[idx+1:]) 
        # 递归右子树,其中右子树的前序遍历的切片为从左子树长度+1处开始一直到尾;中序遍历为总的中序遍历的切片的左子树长度+1处开始一直到尾。
        return root

[点击并拖拽以移动]
​

Guess you like

Origin blog.csdn.net/weixin_45314061/article/details/130836445