二分查找与二叉树排序

#-*-coding=utf-8 -*-


def binarysearch(list, value):
    low = 0
    hight = len(list) - 1
    key = value
    i = 0
    while low <= hight:
        i += 1
        mid = (low + hight) // 2
        if key > list[mid]:
            low = mid + 1
        elif key < list[mid]:
            hight = mid - 1
        else:
            print 'use %d times'%i
            return mid
    return -1


class Btree():
    def __init__(self, value):
        self.left = None
        self.data = value
        self.right = None

    def insertleft(self,value):
        self.left = Btree(value)
        return self.left

    def insertright(self, value):
        self.right = Btree(value)
        return self.right

    def show(self):
        print self.data


def middle_order(root):
    if root.data:
        if root.left:
            middle_order(root.left)
        root.show()
        if root.right:
            middle_order(root.right)


def rmiddle_order(root):#先右后左的中序排序
    if root.data:
        if root.right:
            rmiddle_order(root.right)
        root.show()
        if root.left:
            rmiddle_order(root.left)



def insert(root, key):
    if root.data:
        if key < root.data:
            if root.left:
                insert(root.left, key)
            else:
                key = root.insertleft(key)
        else:
            if root.right:
                insert(root.right,key)
            else:
                key = root.insertright(key)


if __name__ =='__main__':
    #l = [1,2,3,5,9,10,15,16,17,19,23,26,29,34,36,50]
    l=[5, 2, 3, 56,78,1,56,23,51,11,26,34]
    #print binarysearch(l, 50)
    root = Btree(l[0])
    for ele in l[1:]:
        insert(root, ele)
    middle_order(root)
    rmiddle_order(root)
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/MrR1ght/article/details/79269872
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞