【问题标题】:python binary search tree sizepython二叉搜索树大小
【发布时间】:2017-11-15 16:40:13
【问题描述】:

我正在尝试实现二叉搜索树,但我的 size() 方法遇到了问题,该方法计算树中的节点数。

class BSTNode:
def __init__(self, item):

    self._element = item
    self._leftchild = None
    self._rightchild = None
    self._parent = None

这是我的尺寸功能的样子:

def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += 1 + self._leftchild.size()
        if self._rightchild != None:
            size += 1 + self._rightchild.size()
    return size

它高估了树中实际存在的节点数,我不知道为什么,可能是因为它是递归的,但我不确定。

【问题讨论】:

  • size 是指树中的节点数?如果你也能提供一个输入输出的样例,那会很有帮助。
  • 是的,如果不够清楚,对不起

标签: python binary-search-tree nodes counting


【解决方案1】:

替换

size += 1 + self._leftchild.size()

size += self._leftchild.size()

额外的 1 是多算的原因。右孩子也是如此。

【讨论】:

    【解决方案2】:

    您正在计算节点两次。您应该只计算每个节点一次。

    def size(self):
    
        size = 0
        if self != None:
            size += 1
            if self._leftchild != None:
                size += self._leftchild.size()
            if self._rightchild != None:
                size += self._rightchild.size()
        return size
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多