包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.assist = []
def push(self, node):
# write code here
min_value=self.min()
# 辅助栈最开始为空时也要push
if min_value>=node or not min_value:
self.assist.append(node)
else:
self.assist.append(min_value)
self.stack.append(node)
def pop(self):
# write code here
if self.stack:
self.assist.pop()
return self.stack.pop()
else:
return None
def top(self):
# write code here
if self.stack:
return self.stack[-1]
else:
return None
def min(self):
# write code here
if self.assist:
return self.assist[-1]
else:
return None
栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
# 借助辅助栈实现
if not pushV or not popV:
return False
stack=[]
while popV:
# 此处要有对pushV的判断,否则会溢出
if pushV and pushV[0]==popV[0]:
pushV.pop(0)
popV.pop(0)
# 注意此处要有对stack是否为空的判断,否则会溢出
elif stack and stack[-1]==popV[0]:
stack.pop()
popV.pop(0)
elif pushV:
stack.append(pushV.pop(0))
else:
return False
return True
从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
# 先进先出,借助队列
if not root:
return [] # 输出[]而非None
queue=[root]
result=[]
while queue:
temp_queue=[]
for i in queue:
if i.left:
temp_queue.append(i.left)
if i.right:
temp_queue.append(i.right)
result.append(i.val)
queue=temp_queue
return result