和力扣的105题一样~
果然,做了的题是会忘记的,虽然依稀还能记住一点儿。
思路:
#递归base:
当prestart>preend跳出递归~
1、从前序里找根,从中序里找根对应的索引。
2、找到每次左、右子树的起始和终点。
3、递归建立左右子树。
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
return build(pre,0,pre.length-1,vin,0,vin.length);
}
public TreeNode build(int [] pre, int prestart, int preend, int [] vin, int vinstart, int vinend){
if (prestart>preend) return null;
//找根值在中序中对应的索引
int rootvar=pre[prestart];
int flag=0;
for (int i=0; i
方法2:python
class Solution:
def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode:
# write code here
def build(pre,prestart,preend,vin,vinstart,vinend):
flag=0
if prestart>preend: return
#找根对用的索引喵,在中序中找索引~
rootvar=pre[prestart]
for i in range(len(vin)):
if rootvar==vin[i]:
flag=i
break
#建立左右子树喵
leftsize=flag-vinstart
root=TreeNode(rootvar)
root.left=build(pre,prestart+1,prestart+leftsize,vin,vinstart,flag-1)
root.right=build(pre,prestart+leftsize+1,preend,vin,flag+1,vinend)
return root
return build(pre,0,len(pre)-1,vin,0,len(vin)-1)



