广度优先遍历,建一个队列,每次压入左右子节点,知道队列为空。
代码:
# -*- 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
self.st = [root]
self.ans = []
if root == None:
return self.ans
while self.st != None:
if len(self.st) == 0:
break
p = self.st[0]
del self.st[0]
if p.left:
self.st.append(p.left)
if p.right:
self.st.append(p.right)
self.ans.append(p.val)
return self.ans