class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
"""
由于需要逐层打印,那么我们在遍历整棵树的时候就需要维护一个队列。
队列中存储的是下一层从左到右的节点。
具体来说在打印第k层的节点的时候,将该节点的左右子节点按顺序入队即可。递归出口就是队列为空
"""
def PrintFromTopToBottom(self, root):
def helper(root_queue, ans):
# 递归出口即队列为空
if not root_queue:
return
length = len(root_queue)
for i in range(length):
# 对于某个节点,在打印完它的值之后,将其左右子节点先后入队
ans.append(root_queue[i].val)
if root_queue[i].left:
root_queue.append(root_queue[i].left)
if root_queue[i].right:
root_queue.append(root_queue[i].right)
helper(root_queue[length:], ans)
res = []
if not root:
return res
helper([root], res)
return res
def main():
root = TreeNode(8)
root.left = TreeNode(6)
root.right = TreeNode(10)
root.left.left = TreeNode(5)
root.left.right = TreeNode(7)
root.right.left = TreeNode(9)
root.right.right = TreeNode(11)
solution = Solution()
print(solution.PrintFromTopToBottom(root))
if __name__ == ‘__main__‘:
main()
原文:https://blog.51cto.com/jayce1111/2398782