2叉树变双链表

class node:
    def __init__( self , data, left, right):
        self.data = data
        self.left = left
        self.right = right
 
def tree2list(root):
    if root == None :
        return None None
    if root.left == None and root.right == None:
        return root, root
 
    right = root.right
    head, tail = tree2list(root.left)
   
    tail.right = root
    root.left = tail
   
    head2, tail2 = tree2list(right)
    root.right = head2
    head2.left = root
 
    return head, tail2
 
n1 = node(1, NoneNone )
n2 = node(2, NoneNone )
n3 = node(3, n1, n2)
n4 = node(4, NoneNone )
n5 = node(5, n3, n4)
 
root = n5
head, tail = tree2list(root)
it = head
while it != None:
    print it.data
    it = it.right
 
print "—————"
 
it = tail
while it != None:
    print it.data
    it = it.left
    
posted @ 2013-03-22 11:13  ohscar  阅读(168)  评论(0编辑  收藏  举报