使用列表实现二叉树:

def BinarTree(r):
    return [r,[],[]]
 
def insertLeft(root,newBrach):
    t=root.pop(1)
    if len(t)>1:
        root.inset(1,[newBrach,t,[]])
    else:
        root.insert(1,[newBrach,[],[]])
    return root
 
def insertRight(root,newBrach):
    t=root.pop(2)
    if len(t)>1:
        root.insert(2,[newBrach,[],t])
    else:
        root.insert(2,[newBrach,[],[]])
    return root
 
def getRootVal(root):
    return root[0]
 
def setRootVal(root,newVal):
    root[0]=newVal
 
def getLeftChild(root):
    return root[1]
 
def getRihtChild(root):
    return root[2]
 
tree=BinarTree('a')
insertLeft(tree,'b')
insertRight(tree,'c')
insertLeft(getLeftChild(tree),'d')
insertRight(getLeftChild(tree),'e')
insertLeft(getRihtChild(tree),'f')
print(tree)
View Code

相关文章: