【发布时间】:2021-09-02 17:07:14
【问题描述】:
我正在尝试在 python 中实现一些算法,我需要帮助。 给定一些整数数组, 我想建立 BTS 并找到最长的增加子序列。 这个想法是为每个节点提供索引(按插入顺序) 接下来我们要从左树中取出所有索引并将它们放入堆栈 接下来我们要检查上面堆栈中的每个索引,如果我们在树索引中大于当前节点,如果是,我们将其插入堆栈并更新值 max ,这是我们堆栈中的元素数。
我在扫描树并将元素插入堆栈时需要帮助。
到目前为止,这是我的代码:
class Node:
def __init__(self, key, index = -1):
self.right = None
self.left = None
self.key = key
self.index = index
def __str__(self):
return "key: %s, index: %s" % (str(self.key), str(self.index))
def insert(root, key, value=-1):
if root is None:
root = Node(key, value)
else:
if key < root.key:
root.left = insert(root.left, key, value)
elif key > root.key:
root.right = insert(root.right, key, value)
else:
pass
return root
def LeftSideIndices(root):
res = []
if root:
res = LeftSideIndices(root.left)
res.append(root.index)
return res
def InOrderWithInsert(root,A):
newStack = []
if root:
for i in range(0, len(A)):
newStack = upInOrder(root.left,A)
if root.index > A[i]:
newStack.append(root.key)
newStack = newStack + upInOrder(root.right, A)
return newStack
例子:
正确的堆栈应该是:s=[0,2,8,11]
【问题讨论】:
-
你说的是你想做的,但不是你需要帮助的。
-
您有什么特别的原因想用二叉搜索树来做这件事吗?构建 BST 至少是线性的,因此也只需扫描一次列表以找到最长的序列,而无需构建 BST。
-
我更新了我需要帮助的内容。我想这样做的原因是,我在大学的“数据结构”课程的一些练习中看到了这个问题,我只在伪代码中找到了解决方案,如果可能的话,我想实现它。
标签: python algorithm stack binary-search-tree