AcWing 18. 重建二叉树
原题链接
中等
作者:
毛肚先生
,
2020-04-04 10:31:05
,
所有人可见
,
阅读 557
递归实现 $O(n^2)$
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):
if not preorder: return
root = TreeNode(preorder[0])
idx = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:1+idx], inorder[:idx])
root.right = self.buildTree(preorder[1+idx:], inorder[idx+1:])
return root