Python实现二叉树、广度优先搜索、先序遍历、中序遍历、后序遍历

  小编本篇记录了使用Python实现二叉树的相关操作,实现代码如下。

// python实现二叉树相关操作


class Node(object):
    def __init__(self,item):
        self.elem=item
        self.lchild=None
        self.rchild=None

class Tree(object):
    #二叉树
    def __init__(self):
        self.root=None

    #添加节点
    def add(self,item):
        node=Node(item)
        if self.root is None:
            self.root=node
            return

        queue=[self.root]

        while queue:
            cur_node=queue.pop(0)
            if cur_node.lchild is None:
                cur_node.lchild=node
                return
            else:
                queue.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild=node
                return
            else:
                queue.append(cur_node.rchild)

    #广度优先遍历
    def breadth_travel(self):
        queue=[self.root]
        if self.root is None:
            return
        while queue:
            cur_node=queue.pop(0)
            print(cur_node.elem,end=' ')
            if cur_node.lchild is not None:
                queue.append(cur_node.lchild)
            if cur_node.rchild is not None:
                queue.append(cur_node.rchild)

    #先序遍历
    def preorder(self,node):
        if node is None:
            return
        print(node.elem,end=' ')
        self.preorder(node.lchild)
        self.preorder(node.rchild)

    #中序遍历
    def inorder(self,node):
        if node is None:
            return
        self.inorder(node.lchild)
        print(node.elem,end=' ')
        self.inorder(node.rchild)

    #后序遍历
    def postoeder(self,node):
        if node is None:
            return
        self.postoeder(node.lchild)
        self.postoeder(node.rchild)
        print(node.elem,end=' ')


if __name__ == '__main__':
    tree=Tree()
    tree.add(0)
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    tree.add(9)
    #广度优先搜索
    tree.breadth_travel()
    print(' ')
    #先序遍历
    tree.preorder(tree.root)
    print(' ')
    中序遍历
    tree.inorder(tree.root)
    print(' ')
    后序遍历
    tree.postoeder(tree.root)

输出结果如下:
Python实现二叉树、广度优先搜索、先序遍历、中序遍历、后序遍历_第1张图片

参考:https://www.bilibili.com/video/BV17J411i7zS?p=56

你可能感兴趣的:(算法)