简体   繁体   中英

python binary search tree size

im trying to implement a binary search tree and im having trouble with my size() method, which counts the number of nodes in the tree.

class BSTNode:
def __init__(self, item):

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

this is what my size funtion looks like:

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

it overcounts the number of nodes that are actually in the tree and i dont know why, maybe because its recursive but im not sure.

Replace

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

With

size += self._leftchild.size()

That extra 1 is the reason for overcounting. And similarly for right child.

You are counting the nodes twice. You should only be counting each node once.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM