构造二叉树汇总

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

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

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

例如,给出

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

递归求解,把中序遍历的值和下标存入hash表中:

# 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 not preorder or not inorder or len(preorder) == 0 or len(inorder)==0:
            return 
        
        mapping = {}
        for index in range(0,len(inorder)):
            mapping[inorder[index]] = index

        rootval = preorder[0]
        root = TreeNode(rootval)
        rootindex = mapping[rootval]

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

        return root       

 

Lc 106 从中序与后序遍历序列构造二叉树

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

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

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

# 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, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not inorder or not postorder or len(inorder) == 0 or len(postorder)==0:
            return 
        
        mapping = {}
        for index in range(0,len(inorder)):
            mapping[inorder[index]] = index

        rootval = postorder[-1]
        root = TreeNode(rootval)
        rootindex = mapping[rootval]

        root.left = self.buildTree(inorder[0:rootindex],postorder[0:rootindex])
        root.right = self.buildTree(inorder[rootindex+1:],postorder[rootindex:-1])

        return root

 

你可能感兴趣的:(LeetCode)