简体   繁体   English

计算二进制搜索树中的重复节点

[英]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) 其中y是搜索的起始编号(例如,搜索树中的10个数字,我们计算(treeroot,10,0)

However, I tried to put 3 number 10 in and I only receive back the count of 1. 但是,我尝试将3个10放进去,而我只收到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. 我希望您能看到算法的问题:即使您知道9 s的左边或11 s的右边没有10 s,您也将访问树的每个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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