从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

解题思路: 

一个前序遍历和一个中序遍历可以确定一个唯一的二叉树。其中涉及到树的问题,我们可以尝试着是否可以用递归的思想。

前序遍历的第一个元素为根节点(root),查找此根节点在中序遍历的位置,可以得知根节点前面的序列为根的左子树的中序遍历结果,根节点后面的序列为根的右子树的中序遍历结果;假设中序遍历的root前面有left个元素,则在前序遍历中的紧跟root的left个元素preorder[1,left]为root的左子树的前序遍历结果。

# 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, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        
        """
        if inorder==[]:
            return None
        root=TreeNode(preorder[0])
        
        left=inorder.index(root.val)
        
        lchild_insequence=inorder[0:left]#左孩子的中序序列
        rchild_insequence=inorder[left+1:]#右孩子的中序序列
        lchild_presequence=preorder[1:left+1]#左孩子的前序序列
        rchild_presequence=preorder[left+1:]#右孩子的前序序列
        
   
           
        root.left=self.buildTree(lchild_presequence,lchild_insequence)
        root.right=self.buildTree(rchild_presequence,rchild_insequence)
        
        return  root
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """

        if inorder==[]:
            return None
        root = TreeNode(preorder[0])
        #print(preorder,inorder)
        x = inorder.index(root.val)#找到根在中序中的位置
        root.left=self.buildTree(preorder[1:x+1],inorder[0:x])
        root.right=self.buildTree(preorder[x+1:],inorder[x+1:])
        return root

猜你喜欢

转载自blog.csdn.net/qq_39394809/article/details/85373755