我想寫一個函數,它將計算Python中二進制搜索樹中的三種節點類型。它將計算並返回包含0個孩子,1個孩子和2個孩子的節點總數。我已經注意到遞歸方法對於這個而不是迭代方式是最好的。二元搜索樹中的三種節點數(遞歸)
def node_counts(self):
"""
---------------------------------------------------------
Returns the number of the three types of nodes in a BST.
Use: zero, one, two = bst.node_counts()
-------------------------------------------------------
Postconditions:
returns
zero - number of nodes with zero children (int)
one - number of nodes with one child (int)
two - number of nodes with two children (int)
----------------------------------------------------------
"""
zero, one, two = self._node_counts_aux(self._root)
return zero, one, two
def _node_counts_aux(self, node):
zero, one, two = 0, 0, 0
if node is not None:
if not node._right and not node._left:
zero = 1 # I understand that the problem is here.
if node._left and node._right:
two = 1 + self._node_counts_aux(node._left)[2] + self._node_counts_aux(node._right)[2]
if node._left or node._right:
one = 1 + self._node_counts_aux(node._left)[1] + self._node_counts_aux(node._right)[1]
return zero, one, two
"""
I am testing with this Tree:
36
/\
/ \
6 50
/\ /\
4 17 49 84
///\
12 42 65 85
The output with this code comes to: (0, 6, 4).
"""
從某種意義上說,一列是錯誤的,但在某種意義上也是正確的。這不是我關心的問題。 我的擔心是零不算。 零被設置爲0,所以我該如何解決這個問題?
對不起,該函數被稱爲_node_counts_aux。它只是一個輔助函數,它執行主函數的遞歸。 – user1757703 2013-03-20 19:53:33
你在使用任何類別的課程嗎? – 2013-03-20 19:58:12
該類是一個自定義二叉搜索樹ADT。它具有屬性root。它使用另一個具有3個屬性值,左側和右側的短二叉搜索樹節點類。其中左和右基本上是指向它們各自位置的指針。 – user1757703 2013-03-20 20:01:55