python 树形结构

1. 使用dictionary 实现二叉排序树

python 代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# python 二叉树

def create_btree( e ):
    root = {"v":e[0], "left":None, "right":None}
    for i in e[1:-1]:
        insert(root, i)
    return root

def insert(root, i):
    if i==root["v"]:
        return
    if iroot["v"]:
        if root["right"] != None:
            insert(root["right"], i)
        else:
            root["right"] = {"v":i, "left":None, "right":None}

def pre_order(root):
    if root==None:
        return
    pre_order( root["left"] )
    print( root["v"] )
    pre_order( root["right"] )

if __name__ == '__main__':
    l = [ 1, 3, 2, -1, 5, 8 ]
    pre_order( create_btree(l) )

result:



2. 使用类来实现二叉排序树

 #!/usr/bin/python
# -*- coding: utf-8 -*-
# python 二叉树

# 类Node 
class Node:
    def __init__( self, v = None ):
        self.v = v 
        self.left = None 
        self.right = None 
# 类TRee
class Tree:
    def __init__( self ):
        self.root = Node()

    def build(self, e ):
        for i in e:
            self.insert(self.root, i )
    
    def insert(self,root,i):
        if root.v == None:
            root.v = i
            return 
        if root.v == i:
            return 
        if i < root.v :
            if root.left != None:
                self.insert(root.left, i)
            else:
                root.left = Node( i )
        if i > root.v:
            if root.right != None:
                self.insert(root.right, i)
            else:
                root.right = Node( i )
    
    def in_order(self):
        self.in_order_traval( self.root )
    def in_order_traval(self, root):
        if None == root or None == root.v:
            return
        self.in_order_traval( root.left )
        print( root.v )
        self.in_order_traval( root.right )


if __name__ == '__main__':
    l = [ 1, 3, 2, -1, 5, 8 ]    
    tree = Tree()
    tree.build( l )
    tree.in_order()

运行结果:

python 树形结构_第1张图片

你可能感兴趣的:(python,算法,编程,数据结构与算法)