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

原题

 1 class Solution:
 2     def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
 3         def helper(prebegin,preend,inbegin,inend):
 4             if prebegin > preend or inbegin > inend:return None
 5             root = TreeNode(preorder[prebegin])
 6             i = 0
 7             while i + inbegin < inend:
 8                 if inorder[i + inbegin] == preorder[prebegin]:
 9                     break
10                 i += 1
11             root.left = helper(prebegin+1,prebegin+i,inbegin,inbegin + i - 1)
12             root.right = helper(prebegin + i + 1,preend,inbegin + i + 1,inend)
13             return root
14         return helper(0,len(preorder)-1,0,len(inorder)-1);

 

上一篇:p32 二叉树的前序遍历 (leetcode 144)


下一篇:异常:java.sql.SQLIntegrityConstraintViolationException: Column 'category' cannot be null