zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Hadoop之hive 其他
    mac 安装mysql
    Mac OS X【快捷键组合】汇总
    一月一城市,一年一大洲
    自信的男生最有魅力
    Python之路
    Hadoop之伪分布环境搭建
    smb
    Maven 安装以及一些开发技巧
    Hadoop之 hdfs 系统
  • 原文地址:https://www.cnblogs.com/similarface/p/5128797.html
Copyright © 2011-2022 走看看