【发布时间】:2018-07-11 15:47:28
【问题描述】:
我应该如何计算二叉搜索树中只有一个孩子的节点?
def one_child_count(self):
node = self._root
count = self.one_child_count_aux(node)
return count
def one_child_count_aux(self,node):
count = 0
if node :
if node._left is not None and node._right is None:
count += 1
if node._right is not None and node._left is None:
count += 1
else:
if node._left:
count += self.leaf_count_aux(node._left)
if node._right:
count += self.leaf_count_aux(node._right)
return count
我不知道我做错了什么。当我尝试运行我的代码并插入时:
bst.insert(37)
bst.insert(12)
树是这样的:
37
/
12
它应该返回 1,但我得到 2。请帮助我更正我的代码。
【问题讨论】:
-
什么是
leaf_count_aux? -
很抱歉我发现了这个错误感谢您指出@Adam Smith 它现在正在工作:) 这是一个愚蠢的错误
标签: python recursion binary-search-tree