编辑代码

class BiTreeNode:
    #定义二叉树
    def __init__(self,data):
        self.data=data
        self.lchild=None
        self.rchild=None
a=BiTreeNode("0")
b=BiTreeNode("1")
c=BiTreeNode("2")
d=BiTreeNode("3")
e=BiTreeNode("4")
f=BiTreeNode("5")
g=BiTreeNode("6")
h=BiTreeNode("7")
i=BiTreeNode("8")
j=BiTreeNode("9")
a.lchild=b
a.rchild=c
b.lchild=d
b.rchild=e
c.lchild=f
c.rchild=g
d.lchild=h
d.rchild=i
e.lchild=j
#二叉树的遍历 前序(根左右) 中序(左根右) 后序(左右根)
#前序遍历
def pre_order(root):
    if root:
        print(root.data,end=',')
        pre_order(root.lchild)
        pre_order(root.rchild)
def in_order(root):
    if root:
        in_order(root.lchild)
        print(root.data,end=',')
        in_order(root.rchild)
def post_order(root):
    if root:
        post_order(root.lchild)
        post_order(root.rchild)
        print(root.data,end=',')
#二叉树的层序遍历
def travel(root):
    queue=[]
    if root is None:
        return
    else:
        queue.append(root)
    while queue:
        curNode=queue.pop(0)
        print(curNode.data,end=",")
        if curNode.lchild is not None:
            queue.append(curNode.lchild)
        if curNode.rchild is not None:
            queue.append(curNode.rchild)

print("-----------先序-------------")
print(pre_order(e))
print("-----------中序-------------")
print(in_order(e))
print("-----------后序-------------")
print(post_order(e))
print("-----------层序-------------")
print(travel(e))