vlambda博客
学习文章列表

树:前序中序构造二叉树

class TreeNode: def __init__(self,x):    self.val = x    self.left = None    self.right = Nonedef buildTree(preorder, inorder):  pre_r = len(preorder)-1  in_r = len(inorder)-1  def buildt(preorder,pre_l,pre_r,inorder,in_l,in_r):   if pre_l > pre_r or in_l >in_r:      return None    ro = preorder[pre_l]    cur = in_l    while inorder[cur]!=ro:      cur+=1    root = TreeNode(ro)    root.left = buildt(preorder, pre_l+1, pre_l+cur-in_l, inorder, in_l, cur-1) root.right = buildt(preorder, pre_l+cur-in_l+1, pre_r, inorder, cur+1, in_r) return root  return buildt(preorder, 0, pre_r, inorder, 0, in_r)