導航:首頁 > 編程語言 > 用python做一棵簡單的樹

用python做一棵簡單的樹

發布時間:2022-10-02 15:46:34

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或python編程實現steiner樹

這個有幾種方式,你看看哪種更適合你。
把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()

閱讀全文

與用python做一棵簡單的樹相關的資料

熱點內容
程序員級別數學演算法邏輯 瀏覽:895
2k21公園怎麼換伺服器 瀏覽:724
php釋放資料庫連接 瀏覽:722
php網頁抓取工具 瀏覽:726
android設置對齊方式 瀏覽:23
linux創建網頁 瀏覽:280
凈化車間門演算法 瀏覽:934
安卓怎麼搞jpg 瀏覽:546
如來佛祖命令雷神去下界 瀏覽:856
新電腦管家下載好怎麼解壓 瀏覽:530
php獲取介面數據 瀏覽:766
最後的命令 瀏覽:921
如何添加手機app桌面快捷圖標 瀏覽:427
ui設計師與程序員 瀏覽:417
壽司pdf 瀏覽:828
pythonbg是什麼 瀏覽:248
c數值演算法程序大全 瀏覽:787
android整點報時 瀏覽:221
稀土pdf 瀏覽:536
單片機電子鎖 瀏覽:596