剑指offer 从上到下打印二叉树 Posted on 2019-02-21 | 从上到下打印二叉树题目从上往下打印出二叉树的每个节点,同层节点从左至右打印。 方法1234567891011121314151617181920212223# -*- coding:utf-8 -*-# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here if not root: return [] queue=[root] res=[] while queue: for i in range(len(queue)): node=queue.pop(0) res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return res