从有序队列构造平衡二叉树

来源:互联网 发布:淘宝付费推广 编辑:程序博客网 时间:2024/05/09 10:19

瞎写的,随便看看

# coding:utf-8'''Created on 2015年7月27日@author: "zhouyifan"'''import sysclass Tree(object):        def construct_from_array(self, a, root_node):        parent_index = self.get_parent_index(len(a))        root_node.value = a[parent_index]        if parent_index > 0:            ltree_array = a[0:parent_index]            root_node.lchild = Node()            self.construct_from_array(ltree_array, root_node.lchild)        if parent_index < len(a) - 1:            rtree_array = a[parent_index + 1 : len(a)]            root_node.rchild = Node()            self.construct_from_array(rtree_array, root_node.rchild)            def get_parent_index(self, length):        return (length - 1) / 2        def traverse(self, root):        print root.value        if root.lchild:            self.traverse(root.lchild)        if root.rchild:            self.traverse(root.rchild)        def search(self, value, root, l_border, r_border):        if value < root.value :            if root.lchild:                return self.search(value, root.lchild, l_border, root.value)            else:                return root.value                if value >= root.value :            if root.rchild:                return  self.search(value, root.rchild, root.value, r_border)            else:                return r_border                class Node(object):        value = 0    lchild = None    rchild = Noneif __name__ == "__main__":    a = [100, 200, 300, 400, 500, 600, 700]    root = Node()    tree = Tree()    tree.construct_from_array(a, root)    tree.traverse(root)    print tree.search(458, root, 0, sys.maxint)

0 0
原创粉丝点击