Python 递归二叉搜索树

Python 递归二叉搜索树,python,recursion,search,binary,Python,Recursion,Search,Binary,我想用python实现一个包含元素、左、右子元素和父元素的二叉搜索树 class BSTNode: """ An internal node for a BST . """ def __init__(self, item): """ Initialise a BSTNode on creation, with value==item. """ self._element = item self._leftchild = None self._rightch

我想用python实现一个包含元素、左、右子元素和父元素的二叉搜索树

class BSTNode:
""" An internal node for a BST .    """

def __init__(self, item):
    """ Initialise a BSTNode on creation, with value==item. """
    self._element = item
    self._leftchild = None
    self._rightchild = None
    self._parent = None



def __str__(self):
    node = self

    if node != None:
        s = str(node._element)
        if node._leftchild: 
            node._leftchild.__str__()
            s = str(node._element)
            s+= ' '
        elif node._rightchild:
            node._rightchild.__str__()
            s += str(node._element)
        else:
            return s
    else:
        return ''


def add(self, item):
    node = self
    if node:
        if item <node._element :
            if node._leftchild is None:
                node._leftchild = BSTNode(item)
                node._leftchild._parent = node
            else:
                node._leftchild.add(item)
        elif item > node._element:
            if node._rightchild is None:
                node._rightchild = BSTNode(item)
                node._rightchild._parent = node
            else:
                node._rightchild.add(item)


tree = BSTNode(3);
tree.add(7);
 print(tree.__str__());
类节点:
“”“BST的内部节点。”“”
定义初始(自身,项目):
“”“在创建时初始化BSTNode,值==项。”“”
self.\u元素=项目
self.\u leftchild=无
self.\u rightchild=无
self.\u parent=None
定义(自我):
节点=自身
如果节点!=无:
s=str(节点\元素)
if节点。\u leftchild:
节点。\u leftchild.\uuuuu str\uuuuuu()
s=str(节点\元素)
s+=''
elif节点。\u rightchild:
节点。\u rightchild.\uuuuu str\uuuuuu()
s+=str(节点\元素)
其他:
返回s
其他:
返回“”
def添加(自身,项目):
节点=自身
如果节点:
如果项目节点。\u元素:
如果node.\u rightchild为无:
节点。_rightchild=BSTNode(项)
节点。\右子节点。\父节点=节点
其他:
节点。\u rightchild.add(项)
树=节点(3);
添加(7);
打印(tree.\uuuu str\uuuuuuu());

我写了这个程序,但当我运行它时,它不输出任何东西,但它应该输出37(顺序是按顺序遍历)。有人知道我做错了什么吗?

你的
\uu str\uuu
方法不正确。具体地说,您调用左、右子级的
\uuuu str\uuu()
,但不对结果执行任何操作。还请注意,节点可以同时具有左和右子节点(
if…elif
将只检查一个)。如果您点击了
if
elif
块中的一个,您也不会返回
s

您可以将其简化为:

def __str__(self):
    node = self
    if node != None:
        s = str(node._element)
        if node._leftchild: 
            s = node._leftchild.__str__() + s
        if node._rightchild:
            s += ' ' + node._rightchild.__str__()
        return s
    return ''