二叉树(python实现)

二叉树的遍历和添加结点

class Node():
    def __init__(self, item):
        self.elem = item
        self.l_child = None
        self.r_child = None

class Tree():
    def __init__(self):
        self.root = None

    def add(self, elem):
        """为树添加节点"""
        node = Node(elem)
        # 如果树是空的,则对根节点赋值
        if self.root is None:
            self.root = node
            return
        else:
            queue = []
            queue.append(self.root)
            # 对已有节点进行层次遍历
            while queue:
                # 弹出队列的第一个元素
                cur = queue.pop(0)
                if cur.l_child == None:
                    cur.l_child = node
                    return
                elif cur.r_child == None:
                    cur.r_child = node
                    return
                else:
                    # 如果左右子树都不为空,加入队列继续判断
                    queue.append(cur.l_child)
                    queue.append(cur.r_child)

    def preorder(self, root):
        if root == None:
            return
        print(root.elem, end='')
        self.preorder(root.lchild)
        self.preorder(root.rchild)

        def inorder(self, root):
            """递归实现中序遍历"""
            if root == None:
                return
            self.inorder(root.lchild)
            print(root.elem, end=" ")
            self.inorder(root.rchild)

        def postorder(self, root):
            """递归实现后续遍历"""
            if root == None:
                return
            self.postorder(root.lchild)
            self.postorder(root.rchild)
            print(root.elem, end=" ")

        # ××××××××××    广度优先遍历   ×××××××××
        # 从树的root开始,从上到下从从左到右遍历整个树的节点
        def breadth_travel(self):
            """利用队列实现树的层次遍历"""
            if self.root == None:
                return
            queue = [self.root]
            while queue:
                node = queue.pop(0)
                print(node.elem, end=" ")
                if node.lchild != None:
                    queue.append(node.lchild)
                if node.rchild != None:
                    queue.append(node.rchild)

 

posted @ 2019-11-30 10:06  L1m1t  阅读(610)  评论(0编辑  收藏  举报