<commit_before>"""
问题描述：给定一棵二叉树的头结点head,分别实现按层打印和ZigZag打印二叉树的函数。例如，二叉树为：
node1 = Node(1)
node2 = Node(2)
node1.left = node2

node3 = Node(3)
node1.right = node3

node4 = Node(4)
node2.left = node4

node5 = Node(5)
node6 = Node(6)

node3.left = node5
node3.right = node6

node7 = Node(7)
node8 = Node(8)
node5.left = node7
node5.right = node8

按层打印时，输出格式为：
Level 1: 1
Level 2: 2 3
Level 3: 4 5 6
Level 4: 7 8

ZigZag打印时，输出格式为：
Level 1: 1
Level 2: 3 2
Level 3: 4 5 6
Level 4: 8 7

"""<commit_msg>添加二叉树按层次遍历打印<commit_after>"""
问题描述：给定一棵二叉树的头结点head,分别实现按层打印和ZigZag打印二叉树的函数。例如，二叉树为：
head = Node(1)
head.left = Node(2)
head.right = Node(3)
head.left.left = Node(4)
head.right.left = Node(5)
head.right.right = Node(6)
head.right.left.left = Node(7)
head.right.left.right = Node(8)

按层打印时，输出格式为：
Level 1: 1
Level 2: 2 3
Level 3: 4 5 6
Level 4: 7 8

ZigZag打印时，输出格式为：
Level 1: 1
Level 2: 3 2
Level 3: 4 5 6
Level 4: 8 7

"""

from binarytree.toolcls import Node


class PrintZigzag:
    @classmethod
    def print_by_level(cls, root):
        if root is None:
            return
        last = root.value
        nlast = None

        queue = [root]
        level = 1
        while True:
            if len(queue) > 0:
                cur_node = queue.pop(0)
                if cur_node == root:
                    print('Level {}'.format(level), end=':')
                print(cur_node.value, end=' ')
            else:
                break
            if cur_node.left is not None:
                queue.append(cur_node.left)
                nlast = cur_node.left.value
            if cur_node.right is not None:
                queue.append(cur_node.right)
                nlast = cur_node.right.value
            if last == cur_node.value and len(queue) > 0:
                print()
                level += 1
                print('Level {}'.format(level), end=':')
                last = nlast


if __name__ == '__main__':
    head = Node(1)
    head.left = Node(2)
    head.right = Node(3)
    head.left.left = Node(4)
    head.right.left = Node(5)
    head.right.right = Node(6)
    head.right.left.left = Node(7)
    head.right.left.right = Node(8)

    PrintZigzag.print_by_level(head)
{'fraction_non_alphanumeric': 0.12202925045703839, 'fraction_numerical': 0.04524680073126142, 'mean_word_length': 2.118233618233618, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '458130', 'n_tokens_mistral': 955, 'n_tokens_neox': 944, 'n_words': 208}