我正在尝试在Binary搜索树上使用此继任者和前任者。

只是想知道一旦掌握了后继代码,是否可以将其翻转并用于前任代码?
我已经编写了继任者的代码,并尝试将其用于继任者。
但是,即使我尝试放置其他值,我的输出值也不会改变。

下面是我的代码:

成功

def succ(self, key):
    temp = self.root
    prev = None
    if (temp.right is not None):
        temp  = temp.right
        while (temp.left is not None):
            temp = temp.left
        prev = temp
    elif temp.left is not None:e
        temp = temp.left
        while (temp.right is not None):
            temp = temp.right
        prev = temp
    else:
        return None
    return prev.key


前任

def pred(self, key):
        temp = self.root
        prev = None
        #if right is not none, succ lies in the right sub tree
        if (temp.right is not None):
            temp  = temp.right
            while (temp.left is not None):
                #return the node with the minimum key value
                temp = temp.left
            prev = temp
        #if left not none, succ lies in the right sub tree
        elif temp.left is not None:
            #go right till .right is None
            #return the node with the maximum key value
            temp = temp.left
            while (temp.right is not None):
                temp = temp.right
            prev = temp
        else:
            #no succ
            return None
        return prev.key


那个树

    def createTree(self):
        #root
        self.put("F",6)
        #leftSubTree
        self.put("D",4)
        #leftLeftSubTree
        self.put("C",3)
        self.put("B",2)
        self.put("A",1)
        #LeftRightSubTree
        self.put("E",5)
        #RightSubTree
        self.put("I",9)
        #RightLeftSubTree
        self.put("G",7)
        self.put("H",8)
        #RightRightSubTree
        self.put("J",10)

最佳答案

要翻转succ功能并将其转换为pred,您需要将每个left更改为right,并将每个right更改为left

def pred(self, key):
    temp = self.root
    prev = None
    if (temp.left is not None):
        temp  = temp.left
        while (temp.right is not None):
            temp = temp.right
        prev = temp
    elif temp.right is not None:
        temp = temp.right
        while (temp.left is not None):
            temp = temp.left
        prev = temp
    else:
        return None
    return prev.key

10-07 19:11