在AVL树中查找下一个更大的元素

时间:2015-03-16 14:07:03

标签: avl-tree

假设我有跟随AVL树,我的任务是找到给定元素的下一个更大元素(即6为6)。我可以使用什么算法?

AVL tree

1 个答案:

答案 0 :(得分:2)

你通过节点​​递归行走,如果你找到了节点6,那么你就会返回最深的孩子......

伪代码:

 function find_bigger_key(key, node):
    if node = null then
      return null
    else if node.key = key then
       return min_node(node)
    else if key < node.key then
       return find_bigger_key(key, node.left)
    else
       return find_bigger_key(key, node.right)

 function min_node(node):
    if node.ltree = null then
      return node
    else
       return min_node(node.ltree)

这只是一个如何做到的例子,但它取决于你的AVLTree对象模型的样子。

python中的一个示例实现:

class AVLTree(object):
   def __init__(self, key, ltree=None, rtree=None):
      self.key = key ; self.ltree = ltree ; self.rtree = rtree ;
      # perhaps some other attributes here....

   # some other methods here ...

   def find_bigger_key(self, key):
    if not self: return None
    elif self.key == key:
        if self.rtree:
          return self.rtree.min_node()
        else:
          return None
    elif self.key > key:
        return self.left.find_bigger_key(key)
    else:
        return self.right.find_bigger_key(key)

python的示例输出:

>>> # aTree is a avltree object that represents your example
>>> key = 6
>>> found_node = aTree.find_bigger_key(key)
>>> print(found_node)
7
>>> key = 7
>>> found_node = aTree.find_bigger_key(key)
>>> print(found_node)
None