不分行从上往下打印出二叉树的每个节点,同层节点从左至右打印。例如输入{8,6,10,#,#,2,1},如以下图中的示例二叉树,则依次打印8,6,10,2,1(空节点不打印,跳过),请你将打印的结果存放到一个数组里面,返回。
数据范围:
0<=节点总数<=1000
-1000<=节点值<=1000
{8,6,10,#,#,2,1}
[8,6,10,2,1]
{5,4,#,3,#,2,#,1}
[5,4,3,2,1]
class Solution: def PrintFromTopToBottom(self , root: TreeNode) -> List[int]: # write code here ans = [] if root is None: return ans level = [root] while len(level) > 0: next = [] for node in level: ans.append(node.val) if node.left: next.append(node.left) if node.right: next.append(node.right) level = next return ans
import queue class Solution: def PrintFromTopToBottom(self , root: TreeNode) -> List[int]: if root is None: return [] value_list = [] q = queue.Queue() q.put(root) while not q.empty(): node = q.get() if node is None: continue value_list.append(node.val) q.put(node.left) q.put(node.right) return value_list
class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here res,queue = [],[] if root == None: return res queue.append(root) while queue: node = queue.pop(0) res.append(node.val) if node.left != None: queue.append(node.left) if node.right !=None: queue.append(node.right) return res