LeetCode-105、从前序与中序遍历序列构造二叉树-中等
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
代码:
# 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:
return None
val = preorder[0]
tmp = TreeNode(val)
ind = inorder.index(val)
tmp.left = self.buildTree(preorder[1:ind+1], inorder[:ind])
tmp.right = self.buildTree(preorder[ind+1:], inorder[ind+1:])
return tmp
来源:CSDN
作者:clover_my
链接:https://blog.csdn.net/clover_my/article/details/103913709