我正在寻找一种转换我的二叉树结构的算法:来自我自己的类,其中每个节点都有node.value,node.leftChild和node.rightChild。我想将此树转换为Newick格式,因此只能转换树的叶子和结构。
像enter image description here这样的树必须成为(B,(E,F))(所以没有内部节点)
我认为最好的方法是递归遍历我的树并构建字符串,但我总是有特定树的错误。
class binarynode(object):
def __init__(self, value, left = None, right = None,parent =None):
self.parent = parent
self.value = value
self.left = left
self.right = right
def isleaf(self):
return ((self.right == None) and (self.left ==None))
def convertTReeAux(self):
printValue = str(self.value)
if (self.isleaf() and self.parent == None):
ret = '('+printValue+')'
elif (self.isleaf() and (self.parent.left.value == self.value) and (self.parent.right.isleaf())) :
ret = '('+str(printValue)+','
elif (self.isleaf() and self.parent.right.value==self.value and self.parent.left.isleaf() and self.parent.parent !=None and self.parent.parent.right == self.parent):
ret = str(printValue)+'))'
elif (self.isleaf() and self.parent.right.value==self.value and self.parent.left.isleaf()):
ret = str(printValue)+')'
elif (self.isleaf() and (self.parent.left.value == self.value) and (not self.parent.right.isleaf())):
ret = '('+str(printValue)+','
elif (self.isleaf() and self.parent.right.value ==self.value and (not self.parent.left.isleaf())):
ret = ','+str(printValue)+')'
elif( (not self.isleaf()) and (self.parent!= None) and (self.parent.left == self) and (not self.parent.right.isleaf())):
ret = ""
elif( (not self.isleaf()) and (self.parent!= None) and (self.parent.right ==self) and (not self.parent.left.isleaf())):
ret="),"
elif((not self.isleaf()) and (self.parent!= None) and (self.parent.left ==self) and (not self.parent.left.isleaf())):
ret="("
else:
ret = ''
if(self.left != None):
ret += (self.left.convertTReeAux())
if(self.right != None):
ret += (self.right.convertTReeAux())
return ret
答案 0 :(得分:0)
我认为以下代码是您想要的。在Node类中,我定义了函数isLeaf()来检查节点是否为leaf。
class Node:
value = ""
leftChild = None
rightChild = None
def __init__(self, parent):
self.parent = parent
def isLeaf(self):
if (self.leftChild == None and self.rightChild == None):
return True
else:
return False
def convertTreeAux(node, newick):
if node.isLeaf():
newick.append(node.value)
if node.leftChild != None:
newick.append("(")
convertTreeAux(node.leftChild, newick)
newick.append(",")
if node.rightChild != None:
convertTreeAux(node.rightChild, newick)
newick.append(")")
tree = Node(None)
tree.value = "A"
tree.leftChild = Node(tree)
tree.leftChild.value = "B"
tree.rightChild = Node(tree)
tree.rightChild.value = "C"
tree.rightChild.leftChild = Node(tree.rightChild)
tree.rightChild.leftChild.value = "E"
tree.rightChild.rightChild = Node(tree.rightChild)
tree.rightChild.rightChild.value = "F"
newick = []
convertTreeAux(tree, newick)
print (''.join(newick))