题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
Python 代码
广度优先搜索,构造一个辅助队列实现
# -*- 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
if not root:
return []
nodeStack=[root]
result = []
while nodeStack:
nextStack = []
for node in nodeStack:
result.append(node.val)
if node.left:
nextStack.append(node.left)
if node.right:
nextStack.append(node.right)
nodeStack = nextStack
return result
if __name__ == '__main__':
s = Solution()
res = s.PrintFromTopToBottom([1, 2, 5, 3, 4, 6])
print(res)