二叉树的层次遍历-Python 两种写法(列表生成式)
1、扫描一遍 一边生成遍历结果一边给deque添加后继节点
def Print(self, pRoot): # write code here if not pRoot: return [] ans=[] deque=[pRoot] while deque: length=len(deque) tmp=[] for _ in range(length): curr=deque.pop(0) tmp.append(curr.val) if curr.left:deque.append(curr.left) if curr.right:deque.append(curr.right) ans.append(tmp) return ans
2、扫描两遍,生成和添加分开处理
def Print(self, pRoot): # write code here if not pRoot: return [] ans=[] deque=[pRoot] while deque: layer=deque ans.append([x.val for x in deque]) deque=[x for l in layer for x in [l.left,l.right] if x] return ans