题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
这道题就是树的层次遍历,也是广度优先搜索(BFS)
- 将根节点放入队列
- 之后在pop队列的第一个结点时
- 如果它有左孩子就放进队列,有右孩子也放进队列
- 直到队列为空
# -*- 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 []
res=[]
tree=[root]
while len(tree):
root=tree.pop(0)
if root.left:
tree.append(root.left)
if root.right:
tree.append(root.right)
res.append(root.val)
return res
测试用例
if __name__=='__main__':
s=Solution()
root=TreeNode(1)
root.left=TreeNode(2)
root.right=TreeNode(3)
print(s.PrintFromTopToBottom(root))
ps:在二叉树的镜像一题中,打印结果时也有使用该函数