# 面試題32:從上到下打印二叉樹
# 定義二叉樹節點
class BinaryTreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
# 從上到下按層打印
def Print_Up_Down(self, tree):
# 構造隊列
queue = []
# 構造打印結果列表
result = []
if not tree:
return False
queue.append(tree)
while queue:
tree = queue[0]
if tree.left:
queue.append(tree.left)
if tree.right:
queue.append(tree.right)
queue.pop(0)
# 打印結果
result.append(tree.val)
return result
if __name__=="__main__":
# 構造二叉樹
tree = BinaryTreeNode(8)
tree.left = BinaryTreeNode(6)
tree.right = BinaryTreeNode(10)
tree.left.left = BinaryTreeNode(5)
tree.left.right = BinaryTreeNode(7)
tree.right.left = BinaryTreeNode(9)
tree.right.right = BinaryTreeNode(11)
solution = Solution()
print(solution.Print_Up_Down(tree))