剑指offer 把二叉树打印成多行 Posted on 2019-02-21 | 把二叉树打印成多行题目从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。 方法方法1:宽度优先遍历1234567891011121314151617181920212223242526# -*- coding:utf-8 -*-# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # 返回二维列表[[1,2],[4,5]] def Print(self, pRoot): # write code here if not pRoot: return [] import collections queue=collections.deque([(pRoot)]) ans=[] while queue: level=[] for i in range(len(queue)): node=queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) level.append(node.val) ans.append(level) return ans 1234567891011121314151617181920212223242526# -*- coding:utf-8 -*-# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # 返回二维列表[[1,2],[4,5]] def Print(self, pRoot): # write code here if not pRoot: return [] queue=[pRoot] ans=[] while queue: value=[] for i in range(len(queue)): node=queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) value.append(node.val) ans.append(value) return ans