首页 > 编程语言 > 详细

python 二叉树

时间:2016-01-13 23:24:01      阅读:212      评论:0      收藏:0      [点我收藏+]

 

#coding:utf-8
__author__ = similarface

class BinaryTree:
    def __init__(self):
        self.tree=EmptyNode()
    def __repr__(self):
        return repr(self.tree)
    def lookup(self, value):
        return self.tree.lookup(value)
    def insert(self, value):
        self.tree = self.tree.insert(value)

class EmptyNode:
    def __repr__(self):
        return *
    #叶子节点返回false
    def lookup(self,value):
        return False
    #树的低端添加新节点
    def insert(self,value):
        return BinaryNode(self,value,self)

class BinaryNode:
    def __init__(self,left,value,right):
        print(left,value,right)
        self.data, self.left, self.right = value,left,right

    def lookup(self,value):
        if self.data==value:
            return True
        elif self.data>value:
            return self.left.lookup(value)
        else:
            return self.right.lookup(value)
    def insert(self,value):
        if self.data>value:
            self.left=self.left.insert(value)
        elif self.data<value:
            self.right=self.right.insert(value)
        return self

    def __repr__(self):
        return (( %s, %s, %s ) % (repr(self.left), repr(self.data), repr(self.right)))

if __name__=="__main__":
    x=BinaryTree()
    for i in [3,1,2]:
        x.insert(i)

    for i in range(8):
        print((i,x.lookup(i)))
    print(---------------------)
    y=BinaryTree()
    for i in [3,1,9,2,7]:
        y.insert(i)
        print(y)
    print(----------z-----------)
    z=BinaryTree()
    for c in badce:
        z.insert(c)
    print(z)

 

python 二叉树

原文:http://www.cnblogs.com/similarface/p/5128797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!