从上往下打印出二叉树的每个节点,同层节点从左至右打印。

Solutions

每次在打印一个结点时,将其子结点加入到待打印队列中!

# -*- 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 root is None:
            return []
        res = []
        queue = []
        queue.append(root)
        while len(queue):
            res.append(queue[0].val)
            if queue[0].left:
                queue.append(queue[0].left)
            if queue[0].right:
                queue.append(queue[0].right)
            # pop the first node
            queue.pop(0)
        return res

References

  1. 从上往下打印二叉树
  2. Summary of preorder, inorder, postorder, four traversal ways for each