剑指offer60-把二叉树打印成多行**
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
示例
输入 {8,6,10,5,7,9,11}
返回值 [[8],[6,10],[5,7,9,11]]
知识点回顾:
树、BFS
代码
解法一:暴力循环
用两个列表分别保存当前层节点和下一层节点;循环添加当前层节点的左右子节点: 当前层列表,下一层列表 = 下一层列表, [] ;直到当前层为空
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Print(self, pRoot): # write code here if pRoot is None: return [] cur_depth=[pRoot] #当前层 next_depth=[] #下一层 rlt=[] while cur_depth: for i in cur_depth: if i.left: next_depth.append(i.left) if i.right: next_depth.append(i.right) rlt.append([i.val for i in cur_depth]) #要存入数组的是当前层节点的值,注意用法[func(i) for i in list] cur_depth,next_depth=next_depth,[] return rlt
解法二:用队列