shr*_*sva 24 algorithm tree binary-search-tree data-structures
给定BST中的节点,如何找到下一个更高的密钥?
ang*_*son 68
一般方法取决于您的节点中是否有父链接.
然后你选择:
如果您有正确的孩子,请采用这种方法(上述案例1):

如果您没有合适的孩子,请采用以下方法(上述案例2):

然后,您需要对树进行完整扫描,跟踪节点,通常使用堆栈,这样您就可以获得必要的信息,基本上与依赖父链接的第一个方法相同.
对Lasse的答案的 Python代码:
def findNext(node):
if node.rightChild != None:
return findMostLeft(node.rightChild)
else:
parent = node.parent
while parent != None:
if parent.leftChild == node:
break
node = parent
parent = node.parent
return parent
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40571 次 |
| 最近记录: |