神刀安全网

py下的二叉树

原理:

二叉树的先序遍历、后序遍历、中序遍历。。。

代码:

一、py原生数据结构硬实现:
class Node():     def __init__(self,index):         self.index = index         self.left  = None         self.right = None              def __str__(self):         return '%s'%self.index  class Tree():     def __init__(self,nodes):         self.nodes = nodes          def pre(self,node):         print(node)         if node.left is not None:self.pre(node.left)         if node.right is not None:self.pre(node.right)          def lrd(self,node):         if node.left  is not None:self.lrd(node.left)         if node.right is not None:self.lrd(node.right)         print(node)          def ldr(self,node):         if node.left  is not None:self.ldr(node.left)         print(node)         if node.right is not None:self.ldr(node.right) 
运行一下:
nodes = [Node(i) for i in range(8)] nodes[0].left  = nodes[1] nodes[0].right = nodes[2] nodes[1].left  = nodes[3] nodes[1].right = nodes[4] nodes[2].left  = nodes[5] nodes[2].right = nodes[6] nodes[6].left  = nodes[7] tree = Tree(nodes) print('先序遍历:') tree.pre(nodes[0]) print('后序遍历:') tree.lrd(nodes[0]) print('中序遍历:') tree.ldr(nodes[0]) 
运行结果:
先序遍历 01342567后序遍历 34157620中序遍历 31405276 
二、用轮子实现:

py的 networkx 是个很棒的网络图数据结构库,用法见
http://www.cnblogs.com/gispathfinder/p/5790949.html 的翻译:

import networkx as nx import matplotlib.pyplot as plt t = nx.Graph() t.add_nodes_from(range(8)) t.add_edges_from([(0,1),(0,2),(1,3),(1,4),(2,5),(2,6),(6,7)]) nx.draw_networkx(t) 
运行一下:
py下的二叉树

networkx

6行低37行,还顺便画个图给你看,不要太方便有没有!有了轮子谁还傻呵呵自己硬写原生代码啊,所以个人认为只要知道原生代码怎么写的,只用写一次,以后就大胆的用轮子加速我们码字吧!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » py下的二叉树

分享到:更多 ()