Pythonツリー層遍歴&出力層数

1682 ワード

class BTNode(object):
    def __init__(self, key=None, lchild=None, rchild=None):
        self.key = key
        self.lchild = lchild
        self.rchild = rchild

class BiTree(object):
    def __init__(self, data_list):
        self.root = BTNode()
        self.queue = []  #                 ,   root, left, right
        
    def add(self, ele):
        new_node = BTNode(ele)
        self.queue.append(new_node)
        if self.root.key is None:
            self.root = new_node
        else:
            tree_node = self.queue[0]
            if tree_node.lchild is None:
                tree_node.lchild = new_node
            else:
                tree_node.rchild = new_node
                self.queue.pop(0)

    
    def preOrderTrave(self, bt):
        if bt is not None:
            print(bt.key, end=" ")
            self.preOrderTrave(bt.lchild)
            self.preOrderTrave(bt.rchild)
            
    def levelTrave(self, bt):
        if bt is not None:
            queue =[bt]
            level = 0
            while queue:
                print(level, " :", end=":")
                for i in range(len(queue)):
                    bt = queue.pop(0)
                    print(bt.key, end=" ")
                    if bt.lchild != None:
                        queue.append(bt.lchild)
                    if bt.rchild != None:
                        queue.append(bt.rchild)
                level = level + 1
                print("
") btree = BiTree(data_list) for i in range(20): btree.add(i) btree.preOrderTrave(btree.root) print("
") btree.levelTrave(btree.root)