例如,像這樣的樹:薩姆在樹
5
/\
3 6
/\
7 2
print(tree.branchLenSum())
將1+1+2+2=6
樹類:
class BinaryTree:
# Constructor, takes in new key value
def __init__(self, myKey):
self.key = myKey
self.leftChild = None
self.rightChild = None
# Returns root key value
def getRootValue(self):
return self.key
# Changes root key value
def setRootValue(self, newKey):
self.key = newKey
# Returns reference to left child
def getLeftChild(self):
value=None
if self.leftChild!=None:
value=self.leftChild
return value
# Returns reference to right child
def getRightChild(self):
value=None
if self.rightChild!=None:
value = self.rightChild
return value
def insertLeftChild(self, childKey):
newNode = BinaryTree(childKey)
newNode.leftChild = self.leftChild
self.leftChild = newNode
# Inserts key as right child. Existing right child becomes new right child
# of new key
def insertRightChild(self, childKey):
newNode = BinaryTree(childKey)
newNode.rightChild = self.rightChild
self.rightChild = newNode
的我爲此構建的樹:
tree=BinaryTree(5)
tree.insertLeftChild(3)
tree.insertRightChild(6)
nodeA=tree.getLeftChild()
nodeA.insertLeftChild(7)
nodeA.insertRightChild(2)
我有什麼至今:
def branchLenSum(self):
rounds=0
if self.getLeftChild() ==None and self.getRightChild()==None:
return rounds+rounds+1
else:
rounds+=rounds+1
if self.getLeftChild()!=None:
rounds+=self.getLeftChild().branchLenSum()
if self.getRightChild()!=None:
rounds+=self.getRightChild().branchLenSum()
return rounds
我的想法是,每一次旅行到下一個節點,計數器加1 +計數器本身。我想這會得到所有長度的總和。
該解決方案對我來說看起來很好;你的問題是什麼?有什麼不工作? – poke
我發佈的輸入內容效果不佳。我的程序中輸出了'5'。 –
你能以某種方式提供你的樹類的最小版本,所以我們可以測試它嗎?我現在假設'getLeftChild'和'getRightChild'方法工作不正常。 – poke