How to implement a binary search tree in Python?

前端 未结 18 2194
眼角桃花
眼角桃花 2020-11-30 22:25

This is what I\'ve got so far but it is not working:

class Node:
    rChild,lChild,data = None,None,None

    def __init__(self,key):
        self.rChild = N         


        
18条回答
  •  被撕碎了的回忆
    2020-11-30 23:05

    The problem, or at least one problem with your code is here:-

    def insert(self,node,someNumber):
        if node is None:
            node = Node(someNumber)
        else:
            if node.data > someNumber:
                self.insert(node.rchild,someNumber)
            else:
                self.insert(node.rchild, someNumber)
        return
    

    You see the statement "if node.data > someNumber:" and the associated "else:" statement both have the same code after them. i.e you do the same thing whether the if statement is true or false.

    I'd suggest you probably intended to do different things here, perhaps one of these should say self.insert(node.lchild, someNumber) ?

提交回复
热议问题