思路:
题目的要求其实是实现二叉树的层序遍历。
使用两个队列A存放节点,result存放值。先将根节点加入到队列A中,然后遍历队列A中的元素,遍历过程中,访问该元素的左右节点,再将左右子节点加入到队列A中来。
# -*- 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
result=[]
A=[]
A.append(root)
if root==None:
return []
while A:
currentroot=A.pop(0)
result.append(currentroot.val)
if currentroot.left!=None:
A.append(currentroot.left)
if currentroot.right!=None:
A.append(currentroot.right)
return result