4.输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
前序遍历的第一个元素,对应中序遍历的根节点
# 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))
index = tin.index(root.val)
pres = tin[:index]
tins = tin[index+1:]
root.left = self.reConstructBinaryTree(pre, pres)
root.right = self.reConstructBinaryTree(pre, tins)
return root
5.用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型 ,就是以数列模仿栈的功能来实现队列
class Solution:
def __init__(self):
self.stack_a = []
self.stack_b = []
def push(self, node):
# write code here
self.stack_a.append(node)
def pop(self):
# return xx
if self.stack_b:
return self.stack_b.pop()
elif not self.stack_a:
return None
else:
while self.stack_a:
self.stack_b.append(self.stack_a.pop())
return self.stack_b.pop()
6.把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
不知道为什么不能用sort(),只好遍历查找了。因为无序,二分查找有点困难。不过能用分组查找。
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if rotateArray:
min_num = rotateArray[0]
for i in range(0, len(rotateArray)):
if min_num > rotateArray[i]:
min_num = rotateArray[i]
return min_num
else:
return 0