❶ python怎么做二叉查找树
可以的,和C++中类的设计差不多,以下是二叉树的遍历
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
#return BTree(value)
def insertRight(self,value):
self.right=BTree(value)
return self.right
def show(self):
print self.data
def preOrder(node):
node.show()
if node.left:
preOrder(node.left)
if node.right:
preOrder(node.right)
def inOrder(node):
if node:
if node.left:
inOrder(node.left)
node.show()
if node.right:
inOrder(node.right)
if __name__=='__main__':
Root=BTree('root')
A=Root.insertLeft('A')
C=A.insertLeft('C')
D=A.insertRight('D')
F=D.insertLeft('F')
G=D.insertRight('G')
B=Root.insertRight('B')
E=B.insertRight('E')
preOrder(Root)
print 'This is binary tree in-traversal'
inOrder(Root)
❷ 求一个python的三叉树算法
这是网络上的一个版本,我自己做了一点修改,这是一个n叉树,希望对你有所帮助
#!/usr/bin/python
#-*-coding:utf-8-*-
'''
Createdon2014-3-26
@author:qcq
'''
#==============================================================================
#tree.py:
#==============================================================================
#--
#$Revision:1.7$
#$Date:2000/03/2922:36:12$
#modifiedbyqcqin2014/3/27
#modifiedbyqcqin2014/4/23增加了遍历树的非递归版本的广度优先和深度优先
#--
#================================================================
#Contents
#----------------------------------------------------------------
#classTree:Genericn-arytreenodeobject
#classNodeId:Representsthepathtoanodeinann-arytree
#----------------------------------------------------------------
#importstring
classTree:
"""Genericn-arytreenodeobject
Childrenareadditive;noprovisionfordeletingthem.
:0forthefirst
childadded,1forthesecond,andsoon.
modifiedbyqcqin2014/3/27.
Exports:
Tree(parent,value=None)Constructor
.parentIfthisistherootnode,None,otherwise
theparent'sTreeobject.
.childListListofchildren,zeroormoreTreeobjects.
.valueValuepassedtoconstructor;canbeanytype.
.birthOrderIfthisistherootnode,0,otherwisethe
indexofthischildintheparent's.childList
.nChildren()Returnsthenumberofself'schildren.
.nthChild(n)Returnsthenthchild;raisesIndexErrorif
nisnotavalidchildnumber.
.fullPath():.
.nodeId():ReturnspathtoselfasaNodeId.
"""
#---Tree.__init__---
def__init__(self,parent,value=None):
"""ConstructorforaTreeobject.
[if(parentisNoneoraTreeobject)->
if(parentisNone)->
,nochildren,
andvalue(value)
else->
ofparent(parent)andnochildren,andvalue(value)
]
"""
#--1--
self.parent=parent
self.value=value
self.childList=[]
#--2--
#-[if(parentisNone)->
#self.birthOrder:=0
#else->
#parent:=
#self.birthOrder:=sizeofparent's.childList
#-]
ifparentisNone:
self.birthOrder=0
else:
self.birthOrder=len(parent.childList)
parent.childList.append(self)
#---Tree.nChildren---
defnChildren(self):
"""[
]
"""
returnlen(self.childList)
#---Tree.nthChild---
defnthChild(self,n):
"""[if(nisaninteger)->
if(0<=n<(numberofself'schildren)->
returnself's(n)thchild,countingfrom0
else->
raiseIndexError
]
"""
returnself.childList[n]
#---Tree.fullPath---
deffullPath(self):
""".
[returnasequence[c0,c1,...,ci]suchthatselfis
root.nthChild(c0).nthChild(c1).....nthChild(ci),or
anemptylistifselfistheroot]
"""
#--1--
result=[]
parent=self.parent
kid=self
#--2--
#[result+:=childnumbersfromparenttoroot,in
#reverseorder]
whileparent:
result.insert(0,kid.birthOrder)
parent,kid=parent.parent,parent
#--3--
returnresult
#---Tree.nodeId---
defnodeId(self):
""".
"""
#--1--
#[fullPath:=sequence[c0,c1,...,ci]suchthatselfis
#root.nthChild(c0).nthChild(c1).....nthChild(ci),or
#anemptylistifselfistheroot]
fullPath=self.fullPath()
#--2--
returnNodeId(fullPath)
defequals(self,node):
'''
'''
returnself.value==node.value
#===========================================================================
#deletethenodefromthetree
#===========================================================================
defdelete(self):
ifself.parentisNone:
return
else:
#temp=self.birthOrder
'''
ifdeletethemiddletreeobject,
.
'''
self.parent.childList.remove(self.parent.childList[self.birthOrder])
fori,jinzip(range(self.birthOrder+1,self.parent.nChildren()),self.parent.childList[self.birthOrder+1:]):
j.birthOrder=j.birthOrder-1
defupdate(self,value):
'''
'''
self.value=value
def__str__(self):
return"The%dchildwithvalue%d"%(self.birthOrder,self.value)#-----classNodeId-----
classNodeId:
""".
Exports:
NodeId(path):
[->
-id]
.path:[aspassedtoconstructor]
.__str__():[returnselfasastring]
.find(root):
[ifrootisaTreeobject->
treerootedat(root)->
returnthe.valueofthatnode
else->
returnNone]
.isOnPath(node):
[ifnodeisaTreeobject->
->
return1
else->
return0]
"""
#---NodeId.__init__---
def__init__(self,path):
"""ConstructorfortheNodeIdobject
"""
self.path=path
#---NodeId.__str__---
def__str__(self):
"""Returnselfindisplayableform
"""
#--1--
#[L:=alistoftheelementsofself.pathconvertedtostrings]
L=map(str,self.path)
#--2--
#["/"]
returnstring.join(L,"/")
#---NodeId.find---
deffind(self,node):
"""
"""
returnself.__reFind(node,0)
#---NodeId.__reFind---
def__reFind(self,node,i):
"""Recursivenodefindingroutine.Startsatself.path[i:].
[if(nodeisaTreeobject)
and(0<=i<=len(self.path))->
ifi==len(self.path)->
returnnode'svalue
elseifself.path[i:]describesapathfromnode
tosometreeobjectT->
returnT
else->
returnNone]
"""
#--1--
ifi>=len(self.path):
returnnode.value#We'rethere!
else:
childNo=self.path[i]
#--2--
#[->
#child:=thatchildnode
#else->
#returnNone]
try:
child=node.nthChild(childNo)
exceptIndexError:
returnNone
#--3--
#[if(i+1)==len(self.path)->
#returnchild
#elseifself.path[i+1:]describesapathfromnodeto
#sometreeobjectT->
#returnT
#else->
#returnNone]
returnself.__reFind(child,i+1)
#---NodeId.isOnPath---
defisOnPath(self,node):
"""Isself'spathtoorthroughthegivennode?
"""
#--1--
#[nodePath:=pathlistfornode]
nodePath=node.fullPath()
#--2--
#[ifnodePathisaprefixof,oridenticaltoself.path->
#return1
#else->
#return0]
iflen(nodePath)>len(self.path):
return0#Nodeisdeeperthanself.path
foriinrange(len(nodePath)):
ifnodePath[i]!=self.path[i]:
return0#Nodeisadifferentroutethanself.path
return1
❸ 怎样用tk语句在Python下画一棵树
1.代码的结构:
本代码有两个子函数组成,据图有main函数和画树函数组成。
2.编写画树函数:
画树函数,就是用来画出我们的树的一种子函数,代码如下:
deftree(plist,l,a,f):
ifl>5:
lst=[]
forpinplist:
p.forward(l)
q=p.clone()
p.left(a)
q.right(a)
lst.append(p)
lst.append(q)
tree(lst,l*f,a,f)
3.编写main函数:
main函数用来对画树的总体的配置,来画出我们整体的书代码如图下。
defmain():
p=Turtle()
p.color('green')
p.pensize(11)
p.hideturtle()
p.speed(4)
#p.getscreen().tracer(30,0)
p.left(90)
p.penup()
p.goto(0,-100)
p.pendown()
t=tree([p],110,65,0.6375)
4.调用main函数:
在Python语言中与其它的语言不同的是,我们得在脚本中说明我们的主函数,而不是默认的main函数,具体如下。
❹ python怎么动态画出一棵树
fromturtleimportTurtle
deftree(tList,length,angle,factor):
iflength>5:
lst=[]
fortintList:
t.forward(length);
temp=t.clone();
t.left(angle);
temp.right(angle);
lst.append(t);
lst.append(temp);
tree(lst,length*factor,angle,factor);
defmakeTree(x,y):
t=Turtle();
t.color('green');
t.pensize(5);
t.hideturtle();
#t.getscreen().tracer(30,0);
t.speed(10);
t.left(90);
t.penup();
t.goto(x,y);
t.pendown();
t=tree([t],110,65,0.6375);
makeTree(0,0)
❺ 一道算法题,用python初始化一颗二叉树并求解其最短路径的值
二叉树算法,可能按照你的需求不是很多:
下面是我用的一个,不过你可以借鉴一下的:
# -*- coding: cp936 -*-
import os
class Node(object):
"""docstring for Node"""
def __init__(self, v = None, left = None, right=None, parent=None):
self.value = v
self.left = left
self.right = right
self.parent = parent
class BTree(object):
"""docstring for BtTee """
def __init__(self):
self.root = None
self.size = 0
def insert(self, node):
n = self.root
if n == None:
self.root = node
return
while True:
if node.value <= n.value:
if n.left == None:
node.parent = n
n.left = node
break
else:
n = n.left
if node.value > n.value:
if n.right == None:
n.parent = n
n.right = node
break
else:
n = n.right
def find(self, v):
n = self.root # http://yige.org
while True:
if n == None:
return None
if v == n.value:
return n
if v < n.value:
n = n.left
continue
if v > n.value:
n = n.right
def find_successor(node):
'''查找后继结点'''
assert node != None and node.right != None
n = node.right
while n.left != None:
n = n.left
return n
def delete(self, v):
n = self.find(v)
print "delete:",n.value
del_parent = n.parent
if del_parent == None:
self.root = None;
return
if n != None:
if n.left != None and n.right != None:
succ_node = find_successor(n)
parent = succ_node.parent
if succ_node == parent.left:
#if succ_node is left sub tree
parent.left = None
if succ_node == parent.right:
#if succ_node is right sub tree
parent.right = None
if del_parent.left == n:
del_parent.left = succ_node
if del_parent.right == n:
del_parent.right = succ_node
succ_node.parent = n.parent
succ_node.left = n.left
succ_node.right = n.right
del n
elif n.left != None or n.right != None:
if n.left != None:
node = n.left
else:
node = n.right
node.parent = n.parent
if del_parent.left == n:
del_parent.left = node
if del_parent.right == n:
del_parent.right = node
del n
else:
if del_parent.left == n:
del_parent.left = None
if del_parent.right == n:
del_parent.right = None
def tranverse(self):
def pnode(node):
if node == None:
return
if node.left != None:
pnode(node.left)
print node.value
if node.right != None:
pnode(node.right)
pnode(self.root)
def getopts():
import optparse, locale
parser = optparse.OptionParser()
parser.add_option("-i", "--input", dest="input", help=u"help name", metavar="INPUT")
(options, args) = parser.parse_args()
#print options.input
return (options.input)
if __name__ == '__main__':
al = [23, 45, 67, 12, 78,90, 11, 33, 55, 66, 89, 88 ,5,6,7,8,9,0,1,2,678]
bt = BTree()
for x in al :
bt.insert(Node(x))
bt.delete(12)
bt.tranverse()
n = bt.find(12)
if n != None:
print "find valud:",n.value
这个有几种方式,你看看哪种更适合你。
把java封装成restful接口,然后python通过远程调用数据。
使用Pyjnius这个python库。
1
2
3
4
5
6
7
8
9
10
11
12
13
#源代码:github.com/kivy/pyjnius
#文档:pyjnius.readthedocs.org
#也有其他一些的库,如 JPype 或 Py4j ,它们在设计和可用性方面都不是很好。而使用 Jython也不为另一种选择,因为我们想使用 python开发Android项目。
#现在就让我来告诉你,如何简单的使用Pyjnius:
>>> from jnius import autoclass
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> stack.pop()
'world'
>>> stack.pop()
'hello'
❼ 如何采用Python语言绘制一棵树
class node: left=None right=None def __init__(self, parent=None): self.parent=parent 赋值的时候对应就好了。如root=node(),a=node(root),root.left=a,就有点像C语言里的指针了。
❽ python非递归建立二叉树
class Node(object):
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class MyBST(object):
def __init__(self):
self.empty = True
def add(self, value):
if self.empty:
self.root = Node(value)
self.empty = False
cur = self.root
while (True):
if not cur:
cur = Node(value)
break
if value > cur.value:
if cur.value != None:
cur = cur.right
else:
newNode = Node(value)
cur.right = newNode
break
elif value < cur.value:
if cur.value != None:
cur = cur.left
else:
newNode = Node(value)
cur.left = newNode
break
else:
cur.value = value
break
在while(True)循环里添加一个if条件判断
❾ 如何用python构造一个n层的完全二叉树
用python构造一个n层的完全二叉树的代码如下:
typedefstruct{
intweight;
intparent,lchild,rchild;
}HTNode,*HuffmanTree;//动态分配数组存储huffman树
算法设计
voidcreateHuffmantree(){
ht=(HuffmanTree)malloc(m+1)*sizeof(HTNode);//动态分配数组存储huffman树,0号单元未用
//m:huffman树中的结点数(m=2*n-1)
for(i=1;i<=m;++i)
ht[i].parent=ht[i]->lch=ht[i]->rch=0;
for(i=1;i<=n;++i)
ht[i].weight=w[i];//初始化,w[i]:n个叶子的权值
for(i=n+1;i<=m,++i){//建哈夫曼树
select(i-1),s1,s2);//在ht[k](1<=k<=i-1)中选择两个双亲域为零而权值取最小的结点:s1和s2
ht[s1].parent=ht[s2].parent=i;
ht[i].lch=s1;
ht[i].rch=s2;
ht[i].weight=ht[s1].weight+ht[s2].weight;
};
}
❿ python编写欧式二叉树的问题
所以我就遇到了一下几个问题:
1、该怎么把二叉树各个节点连起来?
2、怎么定义内部数据成员?
3、如何实例化左右孩子?
在网上也没找到比较简单比较通用的Python二叉树类实现,所以我花了点时间自己写一个。
[python] view plain 在CODE上查看代码片派生到我的代码片
class Tree:
def __init__(self, val = '#', left = None, right = None):
self.val = val
self.left = left
self.right = right
#前序构建二叉树
def FrontBuildTree(self):
temp = input('Please Input: ')
node = Tree(temp)
if(temp != '#'):
node.left = self.FrontBuildTree()
node.right = self.FrontBuildTree()
return node#因为没有引用也没有指针,所以就把新的节点给返回回去
#前序遍历二叉树
def VisitNode(self):
print(self.val)
if(self.val != '#'):
self.left.VisitNode()
self.right.VisitNode()
if __name__ == '__main__':
root = Tree()
root = root.FrontBuildTree()
root.VisitNode()