python - python中的二叉搜索树递归实现

标签 python python-2.7 python-3.x recursion data-structures

我正在尝试使用递归在 Python 中实现二叉搜索树。我被困在我的程序中发生的一些无限递归中。我通过传递地址和数据对函数 RecursBST 进行递归调用,直到顶部向下遍历到它的左子或右子的 None 值.

class createnode:
    def __init__(self,data):
        self.root=data
        self.left=None
        self.right=None

class createbinarysearchtree:
    def __init__(self, data = None):
        self.top=None   

    def RecursBST(self,top,data):            
        if self.top is None:
            self.top=createnode(data)                
        elif  self.top.root>data:
            self.top.left=self.RecursBST(self.top.left,data)
        elif  self.top.root<data:
            self.top.right=self.RecursBST(self.top.right,data)

conv=createbinarysearchtree();
conv.RecursBST(conv.top,50)
conv.RecursBST(conv.top,40)

我遇到了以下错误:

 self.top.left=self.RecursBST(self.top.left,data)
RuntimeError: maximum recursion depth exceeded

最佳答案

您的代码缺少提供递归终止条件和更改递归状态的代码:

来自 https://en.wikipedia.org/wiki/Recursion_termination

In computing, recursion termination is when certain conditions are met and a recursive algorithm stops calling itself and begins to return values.This happens only if, with every recursive call, the recursive algorithm changes its state and moves toward the base case.

如果递归永远不会结束,那么它必须遇到最大递归深度限制。

您在代码中不会遇到此问题的唯一情况是没有顶级节点,否则递归是无限的。

有一个很好的工具,您可以使用它来可视化您的代码或其他答案中提供的代码的作用:

http://www.pythontutor.com/

以便您了解实际发生的情况以及这是否是您想要实现的目标。

这是在您的问题的另一个答案中运行 bones.felipe 提供的代码的最终结果:pythontutor-result-image

FMc 对您的问题的评论已经很好地回答了您面临的问题(引用):

Typically a BST has three methods: insert(), delete(), and search(). Your current implementation is confusing things by performing insertion-related work (creating a node) with search-related work. Also, there's a related style note that adds to this general confusion: normally classes are things or nouns (BinarySearchTree or Node) not actions (createnode or createbinarysearchtree).

关于python - python中的二叉搜索树递归实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090304/

相关文章:

python - 使用 Tornado 为我的 Python 应用程序提供一个 Web 界面来监控它

python - 检查时间跨度之间的重叠

python - 输入元组并选择奇数或偶数

python - Python Telegram Bot 中的音频段库

python - 独特页面的数据框摘要

python - 在项目列表上调用一个函数的最干净的方法

python - SQLAlchemy , 属性错误 : 'tuple' object has no attribute 'foreign_keys'

python - 为时代换弦

Python Gtk 按钮

python - 如何使已打开的文件可读(例如 sys.stdout)?