运行时间:64ms
占用内存:5712k
递归还是不熟,或者说是树不熟
注意递归的终止条件,是大于不是大于等于
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
def findroot(pre,pl,pr,tin,tl,tr):
if (pl>pr) or (tl>tr):
return None
root = TreeNode(pre[pl])
i = tin.index(pre[pl])
root.left = findroot(pre,pl+1,pl+(i-tl),tin,tl,i-1)
root.right = findroot(pre,(i-tl)+pl+1,pr,tin,i+1,tr)
return root
return findroot(pre,0,len(pre)-1,tin,0,len(tin)-1)
————————————————————————————————————————
上面是很容易理解的地推思路,就是左右的界限每次都要修改
下面这种递归思想很不容易想到,利用pop(),每次删掉查到的那个根节点,而因为是左子树先搜查,所以所有左子树的根都会被删除最后留下右子树的根。
运行时间:48ms
占用内存:5712k
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root = TreeNode(pre.pop(0))
i = tin.index(root.val)
root.left = self.reConstructBinaryTree(pre,tin[:i])
root.right = self.reConstructBinaryTree(pre,tin[i+1:])
return root