python中如何创建一颗多叉树,python 多叉树 四叉树

#coding=utf-8

"""

@des:多叉树--这里定义的4叉树

"""

class node:

def __init__(self, data):

self._data = data

self._children = []

def getdata(self):

return self._data

def getchildren(self):

return self._children

def add(self, node):

##if full

if len(self._children) == 4:

return False

else:

self._children.append(node)

def go(self, data):

for child in self._children:

if child.getdata() == data:

return child

return None

class tree:

def __init__(self):

self._head = node('header')

def linktohead(self, node):

self._head.add(node)

def insert(self, path, data):

cur = self._head

for step in path:

if cur.go(step) == None:

return False

else:

cur = cur.go(step)

cur.add(node(data))

return True

def search(self, path):

cur = self._head

for step in path:

if cur.go(step) == None:

return None

else:

cur = cur.go(step)

return cur

if __name__=="__main__":

'''

define node

'''

a = node('A')

b = node('B')

c = node('C')

d = node('D')

e = node('E')

f = node('F')

g = node('G')

h = node('H')

i = node('I')

j = node('J')

k = node('K')

l = node('L')

m = node('M')

n = node('N')

o = node('O')

'''

adding node to build true

'''

a.add(b)

a.add(g)

a.add(h)

b.add(c)

b.add(e)

g.add(i)

g.add(j)

g.add(k)

g.add(l)

h.add(m)

h.add(n)

h.add(o)

c.add(d)

c.add(f)

i.add(node(29))

j.add(node(28))

k.add(node(27))

l.add(node(26))

m.add(node(25))

n.add(node(24))

o.add(node(23))

f.add(node(30))

tree = tree()

tree.linktohead(a)

#testcase

print 'Node',tree.search("ABE").getdata()

print 'Node',tree.search("ABC").getdata()

print 'Node',tree.search("AHM").getdata()

tree.insert("ABCD", 1)

for i in d.getchildren():

print 'value after', d.getdata(),' is ', i.getdata()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值