AcWing 18. 重建二叉树 Python
原题链接
中等
作者:
lihaitao
,
2021-04-27 10:32:09
,
所有人可见
,
阅读 638
分治法
Python 代码
# 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 not preorder:
return None
for i in range(len(inorder)):
if inorder[i] == preorder[0]:
inorder_left = inorder[:i]
inorder_right = inorder[i + 1 : ]
preorder_left = preorder[1 : len(inorder_left) + 1]
preorder_right = preorder[len(inorder_left) + 1 :]
root = TreeNode(preorder[0])
root.left = self.buildTree(preorder_left, inorder_left)
root.right = self.buildTree(preorder_right, inorder_right)
return root