构建三叉树的算法,求救高手!!!!!
关注:109 答案:2 信息版本:手机版 电脑版
解决时间 2021-01-24 17:11
提问者嗿恋仯囡
2021-01-24 00:24
有道题目需要写一函数来构造一个三叉树,已知:标准链式存储结构,指向跟的指针变量是root.....///高手给出一个算法呀,不胜感激!!!
最佳答案
二级知识专家暖心欧巴
2021-01-24 01:15
drty
全部回答
1楼無字情書
2021-01-24 01:25
这是网络上的一个版本,我自己做了一点修改,这是一个n叉树,希望对你有所帮助
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
created on 2014-3-26
@author: qcq
'''
#==============================================================================
# tree.py: generic tree node object for python
#==============================================================================
#--
# $revision: 1.7 $
# $date: 2000/03/29 22:36:12 $
# modified by qcq in 2014/3/27
# modified by qcq in 2014/4/23 增加了遍历树的非递归版本的广度优先和深度优先
#--
#================================================================
# contents
#----------------------------------------------------------------
# class tree: generic n-ary tree node object
# class nodeid: represents the path to a node in an n-ary tree
#----------------------------------------------------------------
#import string
class tree:
""" generic n-ary tree node object
children are additive; no provision for deleting them.
the birth order of children is recorded: 0 for the first
child added, 1 for the second, and so on.
modified by qcq in 2014/3/27. add the function for deleting one node in the tree structure
exports:
tree(parent, value=none) constructor
.parent if this is the root node, none, otherwise
the parent's tree object.
.childlist list of children, zero or more tree objects.
.value value passed to constructor; can be any type.
.birthorder if this is the root node, 0, otherwise the
index of this child in the parent's .childlist
.nchildren() returns the number of self's children.
.nthchild(n) returns the nth child; raises indexerror if
n is not a valid child number.
.fullpath(): returns path to self as a list of child numbers.
.nodeid(): returns path to self as a nodeid.
"""
# - - - t r e e . _ _ i n i t _ _ - - -
def __init__ ( self, parent, value=none ):
""" constructor for a tree object.
[ if (parent is none or a tree object) ->
if (parent is none) ->
return a new tree object with no parent, no children,
and value (value)
else ->
return a new tree object added as the next new child
of parent (parent) and no children, and value (value)
]
"""
#-- 1 --
self.parent = parent
self.value = value
self.childlist = []
#-- 2 --
#-[ if (parent is none) ->
# self.birthorder := 0
# else ->
# parent := parent with self added as its next child
# self.birthorder := size of parent's .childlist
#-]
if parent is none:
self.birthorder = 0
else:
self.birthorder = len(parent.childlist)
parent.childlist.append ( self )
# - - - t r e e . n c h i l d r e n - - -
def nchildren ( self ):
""" [ return the number of children of self
]
"""
return len(self.childlist)
# - - - t r e e . n t h c h i l d - - -
def nthchild ( self, n ):
""" [ if (n is an integer) ->
if (0 <= n
return self's (n)th child, counting from 0
else ->
raise indexerror
]
"""
return self.childlist[n]
# - - - t r e e . f u l l p a t h - - -
def fullpath ( self ):
"""returns a list of child numbers from root to self.
[ return a sequence [c0, c1, ..., ci] such that self is
root.nthchild(c0).nthchild(c1). ... .nthchild(ci), or
an empty list if self is the root ]
"""
#-- 1 --
result = []
parent = self.parent
kid = self
#-- 2 --
# [ result +:= child numbers from parent to root, in
# reverse order ]
while parent:
result.insert ( 0, kid.birthorder )
parent, kid = parent.parent, parent
#-- 3 --
return result
# - - - t r e e . n o d e i d - - -
def nodeid ( self ):
"""returns the path to self in the tree as a nodeid.
"""
#-- 1 --
# [ fullpath := sequence [c0, c1, ..., ci] such that self is
# root.nthchild(c0).nthchild(c1). ... .nthchild(ci), or
# an empty list if self is the root ]
fullpath = self.fullpath()
#-- 2 --
return nodeid ( fullpath )
def equals(self, node):
'''judge if the two tree object is equal
'''
return self.value == node.value
#===========================================================================
# delete the node from the tree
#===========================================================================
def delete(self):
if self.parent is none:
return
else:
#temp = self.birthorder
'''
if delete the middle tree object,
then move the tree object behind this tree object forward.
'''
self.parent.childlist.remove(self.parent.childlist[self.birthorder])
for i,j in zip(range(self.birthorder + 1, self.parent.nchildren()), self.parent.childlist[self.birthorder + 1:]):
j.birthorder = j.birthorder - 1
def update(self, value):
'''
update the value of this tree object
'''
self.value = value
def __str__(self):
return "the %d child with value %d"%(self.birthorder, self.value)
# - - - - - c l a s s n o d e i d - - - - -
class nodeid:
"""represents the location of a node in a tree as a path from the root.
exports:
nodeid(path):
[ if path is a list of zero or more nonnegative integers ->
return a new nodeid object representing that node-id ]
.path: [ as passed to constructor ]
.__str__(): [ return self as a string ]
.find(root):
[ if root is a tree object ->
if self describes a path to a node that exists in the
tree rooted at (root) ->
return the .value of that node
else ->
return none ]
.isonpath(node):
[ if node is a tree object ->
if the path from the root to node is a prefix of self ->
return 1
else ->
return 0 ]
"""
# - - - n o d e i d . _ _ i n i t _ _ - - -
def __init__ ( self, path ):
"""constructor for the nodeid object
"""
self.path = path
# - - - n o d e i d . _ _ s t r _ _ - - -
def __str__ ( self ):
"""return self in displayable form
"""
#-- 1 --
# [ l := a list of the elements of self.path converted to strings ]
l = map ( str, self.path )
#-- 2 --
# [ return the elements of l concatenated and separated by "/" ]
return string.join ( l, "/" )
# - - - n o d e i d . f i n d - - -
def find ( self, node ):
"""locate the tree node described by self and return its value
"""
return self.__refind ( node, 0 )
# - - - n o d e i d . _ _ r e f i n d - - -
def __refind ( self, node, i ):
"""recursive node finding routine. starts at self.path[i:].
[ if (node is a tree object)
and (0 <= i <= len(self.path)) ->
if i == len(self.path) ->
return node's value
else if self.path[i:] describes a path from node
to some tree object t ->
return t
else ->
return none ]
"""
#-- 1 --
if i >= len(self.path):
return node.value # we're there!
else:
childno = self.path[i]
#-- 2 --
# [ if node has a child of number childno ->
# child := that child node
# else ->
# return none ]
try:
child = node.nthchild ( childno )
except indexerror:
return none
#-- 3 --
# [ if (i+1) == len(self.path) ->
# return child
# else if self.path[i+1:] describes a path from node to
# some tree object t ->
# return t
# else ->
# return none ]
return self.__refind ( child, i+1 )
# - - - n o d e i d . i s o n p a t h - - -
def isonpath ( self, node ):
"""is self's path to or through the given node?
"""
#-- 1 --
# [ nodepath := path list for node ]
nodepath = node.fullpath()
#-- 2 --
# [ if nodepath is a prefix of, or identical to self.path ->
# return 1
# else ->
# return 0 ]
if len(nodepath) > len(self.path):
return 0 # node is deeper than self.path
for i in range(len(nodepath)):
if nodepath[i] != self.path[i]:
return 0 # node is a different route than self.path
return 1
我要举报
如以上信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
推荐资讯
大家都在看