• python 二叉树


    #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)
  • 相关阅读:
    MAC终端配置
    SCIENCE公布125个科学前沿问题
    【Python3】内存释放机制
    【Python3】装饰器
    【Python3】迭代器&装饰器
    【Python3】内置函数
    【Python3】高阶函数
    【Python3】匿名函数
    【Python3】递归函数
    【Python3】嵌套函数
  • 原文地址:https://www.cnblogs.com/similarface/p/5128797.html
Copyright © 2020-2023  润新知