简体   繁体   中英

Count repetitive node in Binary Search Tree

I am trying to write a function to count the repetitive node in a Binary Search Tree (assume that this tree accept repetition). Here is a line of code that I have

def count(treeroot,item,y):
if treeroot==None:
    return 0
elif treeroot.getData()==item:
    return 1
else:
    return count(treeroot.getLeft(),item,y)+count(treeroot.getRight(),item,y)

where y is the starting number of the search (such as search for how many 10 in the tree, we do count(treeroot,10,0)

However, I tried to put 3 number 10 in and I only receive back the count of 1.

Can anyone tell me what is wrong with my code and how to fix it

You stop recursing down the tree as soon as you found the first item. You need to keep recursing:

def count(treeroot,item,y):
    if treeroot==None:
        return 0
    elif treeroot.getData()==item:
        return 1 + count(treeroot.getLeft(),item,y)+count(treeroot.getRight(),item,y)
    else:
        return count(treeroot.getLeft(),item,y)+count(treeroot.getRight(),item,y)

I hope you see the problem with your algorithm though: You will visit each and every node of the tree, even if you know that there will be no 10 s to the left of 9 s or to the right of 11 s.

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