자바·파이썬·자바스크립트/파이썬 프로그래밍

이진나무의 구현

바로이순간 2011. 12. 6. 17:39

def preorder(t):
    if t==None: return
    print t[0],
    preorder(t[1])
    preorder(t[2])
def inorder(t):
    if t==None: return
    inorder(t[1])
    print t[0],
    inorder(t[2])
def postorder(t):
    if t==None: return
    postorder(t[1])
    postorder(t[2])
    print t[0],
def levelorder(t):
    q=[t]
    while q:
        x=q.pop(0)
        print x[0],
        if x[1]: q.append(x[1])
        if x[2]: q.append(x[2])
def insert(t, k):
    if t==None:
    return [k,None,None]
    pp,p=t,t
    while p:
        if k==p[0]:
            print '***Error, duplicated key***'
            return t
        if k<p[0]:
            pp,p=p,p[1]
        else:
            pp,p=p,p[2]
    if k<pp[0]:
        pp[1]=[k,None,None]
    else:
        pp[2]=[k,None,None]
    return t
tree=None
tree=insert(tree,'C')
tree=insert(tree,'H')
tree=insert(tree,'E')
tree=insert(tree,'O')
tree=insert(tree,'N')
tree=insert(tree,'G')
tree=insert(tree,'J')
tree=insert(tree,'U')
tree=insert(tree,'I')
tree=insert(tree,'V')
tree=insert(tree,'R')
tree=insert(tree,'S')
tree=insert(tree,'T')
tree=insert(tree,'Y')
preorder(tree)
print '-- preorder'
inorder(tree)
print '-- inorder'
postorder(tree)
print '-- postorder'
levelorder(tree)
print '-- levelorder'