二叉树的层序遍历,本质就是广度遍历有向图。都要用到队列。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
deque = []
if not root:
return []
new = [root]
while len(new):
temp = new.pop(0)
deque.append(temp.val)
if temp.left:
new.append(temp.left)
if temp.right:
new.append(temp.right)
return deque