在二进制搜索中查找2个节点的路径

2024-04-20 08:43:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,应该可以找到2个节点之间的路径。问题是,如果节点2大于节点1,则无法区分它是父节点还是正确的子节点,我现在不知道如何更正此问题。我想也许交换元素2和1会起作用,但那只会使顺序错误

def _find_path(self, element_1, element_2, nature):

    if element_1 !=None and element_2 != None:
        if element_1.key == element_2.key:
            self.list_path.append(element_1)
        else:
            if(element_1.key == self.root.key or element_2.key == self.root.key):
                if(element_2.key > element_1.key):
                    self.list_path.append(element_1)
                    self._find_path(element_1.rightChild, element_2, nature)
                if (element_2.key < element_1.key):
                    self.list_path.append(element_1)
                    self._find_path(element_1.leftChild, element_2, nature)
            else:
                    if(element_1.key < self.root.key and element_2.key < self.root.key or element_1.key > self.root.key and element_2.key > self.root.key):
                        if element_2.key > element_1.key:
                            self.list_path.append(element_1)
                            self._find_path(element_1.parent, element_2, nature)
                        if element_2.key < element_1.key:
                            self.list_path.append(element_1)
                            self._find_path(element_1.leftChild, element_2, nature)
                        else:
                            if element_1.key == element_2.key:
                               return [element_1]
                            res = self._find_path(element_1.leftChild, element_2,nature)
                            if res:
                                self.steps += 1
                                return [element_1] + res
                            res = self._find_path(element_1.rightChild, element_2,nature)
                            if res:
                                self.steps += 1
                                return [element_1] + res
                    else:
                        if(element_1.key < self.root.key and element_2.key > self.root.key):
                            self.list_path.append(element_1)
                            self._find_path(element_1.parent, element_2, nature)
                        else:
                            self.list_path.append(element_1)
                            self._find_path(element_1.parent, element_2, nature)
    return self.list_path

Tags: andpathkeyselfreturnif节点res