# 一、递归yield使用

## 1、嵌套列表展开

def flatten(nested):
if type(nested)==list:
for sublist in nested:
for i in flatten(sublist):
yield i
else:
yield nested
print(list(flatten([[[1],2],3,4,[5,[6,7]],8])))#结果为[1,2,3,4,5,6,7,8]

## 2、树的后序遍历

    def postorderTraversal(self, root):
def iter(root):
if root:
for x in iter(root.left):
yield x
for x in iter(root.right):
yield x
yield root.val
return list(iter(root))

## 2、建立所有的二叉搜索树

class TreeNode:
def __init__(self,root):
self.val=root
self.left=None
self.right=None#用生成器建立所有树
def builtTree(start,end):
if start>end:
yield None
for j in range(start,end+1):
for j_left in builtTree(start,j-1):
for j_right in builtTree(j+1,end):
root=TreeNode(j)
root.left=j_left
root.right=j_right
yield root#调用建树函数
def test(n):
if n==0:
return []
return list(builtTree(1,n))

## 2、二叉搜索树按序输出

class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack=[]
while root:
self.stack.append(root)
root=root.left

def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack)>0

def next(self):
"""
:rtype: int
"""
node=self.stack.pop()
x=node.right
while x:
self.stack.append(x)
x=x.left
return node.val

# 二、itertools

## 1、chain（）：

from itertools import chain

for c in itertools.chain('ABC', 'XYZ'):
print(c)
# 迭代效果：'A' 'B' 'C' 'X' 'Y' 'Z'

a = [1, 2, 3, 4]
b = [‘x’, ‘y’, ‘z’]
for x in chain(a, b):
print(x)

#迭代结果：1,2,3,4,'x','y','z'

posted on 2018-06-24 17:36  吱吱了了  阅读(688)  评论(0编辑  收藏  举报